redis

package
v1.0.11 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 27, 2023 License: MIT Imports: 10 Imported by: 0

README

Redis Client

This is a Redis client wrapper for Golang that provides a simplified interface to interact with Redis.

Installation

To use this library install using the go get commant

go get -u github.com/SimifiniiCTO/simfiny-core-lib/database/redis

Usage

To use this library first import

import github.com/SimifiniiCTO/simfiny-core-lib/database/redis
import github.com/SimifiniiCTO/simfiny-core-lib/signals

Create The Client

To create a new Redis client, use the New function:

    stopCh := signals.SetupSignalHandler()
    opts := []redis.Options{
        redis.WithLogger(zap.L()),
        redis.WithTelemetrySdk(&instrumentation.Client{}),
        redis.WithURI(host),
        redis.WithServiceName(serviceName), 
        redis.WithCacheTTLInSeconds(cacheTTLInSeconds),
    }

    c, err := redis.New(stopCh, opts...)
    if err != nil {
        ...
    }

Where:

  • host: the Redis server host (string).
  • serviceName: the service initialization the redis connection
  • logger: zap logger instance
  • cacheTTLInSeconds: the TTL (in seconds) for cache entries (int).
  • telemetrySdk: the telemetry SDK to use (an object implementing the ITelemetrySdk interface).

Reading data from Redis

To read data from Redis, use the Read function:

value, err := client.Read(ctx, key)
if err != nil {
    // handle error
}

Where:

  • ctx: the context (context.Context) for the Redis read operation.
  • key: the key (string) for the data to read.

Deleting data from Redis

To delete data from Redis, use the Delete function:

err := client.Delete(ctx, key)
if err != nil {
    // handle error
}

Where:

  • ctx: the context (context.Context) for the Redis delete operation.
  • key: the key (string) for the data to read.

Testing

To run the unit tests, use the go test command:

go test -v

Contributing

Contributions to this Redis client are welcome. To contribute, follow these steps:

  • Fork this repository.
  • Create a new branch: git checkout -b my-new-feature.
  • Make changes and add tests for the new feature.
  • Run tests and ensure they pass: go test -v.
  • Commit your changes: git commit -am 'Add some feature'.
  • Push to the branch: git push origin my-new-feature.
  • Create a new Pull Request.

License

This Redis client is released under the MIT License. See LICENSE for more information.

Documentation

Overview

Package rediswrapper provides a simple Redis client wrapper to easily interface with Redis server for caching and storage purposes.

The Redis client implementation is based on the popular "github.com/go-redis/redis/v8" package, and provides simple functions for key-value set, get, delete, and hash operations.

To use the Redis client, simply create a new client using the NewRedisClient function, passing in the Redis server host and port, as well as any authentication details if necessary.

The Redis client is thread-safe and supports connection pooling to minimize overhead when making frequent connections to the Redis server.

Example usage:

package main

import (

"fmt"

"github.com/example/rediswrapper"

)

func main() {
   // Create a new Redis client
   client := rediswrapper.NewRedisClient("localhost:6379", "", 0)

   // Set a value in Redis
   err := client.SetValue("key", "value", 0)
   if err != nil {
       fmt.Println("Error setting value:", err)
       return
   }

   // Get a value from Redis
   value, err := client.GetValue("key")
   if err != nil {
       fmt.Println("Error getting value:", err)
       return
   }
   fmt.Println("Value:", value)
}

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidURI               = errors.New("invalid redis URI")
	ErrInvalidServiceName       = errors.New("invalid service name")
	ErrInvalidLogger            = errors.New("invalid logger")
	ErrInvalidTelemetrySdk      = errors.New("invalid telemetry SDK")
	ErrInvalidPool              = errors.New("invalid pool")
	ErrInvalidCacheTTLInSeconds = errors.New("invalid cache TTL in seconds")
)

Functions

This section is empty.

Types

type Client

type Client struct {

	// The `URI` field is a string that represents the connection URI for the Redis database that the
	// client will be interacting with. It could include information such as the host, port, and
	// authentication credentials needed to establish a connection.
	URI string
	// The `Logger` field is a pointer to a `zap.Logger` instance, which is a structured, leveled logging
	// library for Go. It is used to log messages and events related to the `Client` struct and its
	// operations. This allows for more detailed and organized logging, which can be helpful for debugging
	// and troubleshooting issues with the Redis client.
	Logger *zap.Logger
	// contains filtered or unexported fields
}

The `Client` type contains various fields related to a Redis client in a Go program, including a connection pool, cache TTL, telemetry SDK, URI, and logger. @property pool - A redis connection pool used to manage connections to a Redis server. @property {string} serviceName - The `serviceName` property is a string that represents the name of the service that is using this `Client` struct. @property {int} cacheTTLInSeconds - cacheTTLInSeconds is a property of the Client struct that represents the time-to-live (TTL) value in seconds for cached data. This property is used to determine how long cached data should be considered valid before it needs to be refreshed or retrieved again from the data source. @property telemetrySdk - The `telemetrySdk` property is a pointer to an instance of the `Client` struct from the `instrumentation` package. This is likely used for collecting and reporting telemetry data related to the Redis client's usage and performance. @property {string} URI - The URI property is likely a string that represents the connection URI for the Redis database that the client will be interacting with. It could include information such as the host, port, and authentication credentials needed to establish a connection. @property Logger - The Logger property is a pointer to a zap.Logger instance, which is a structured, leveled logging library for Go. It is used to log messages and events related to the Client struct and its operations.

func New

func New(stopCh <-chan struct{}, opts ...Option) (*Client, error)

New creates a new client with optional configurations and a stop channel.

func (*Client) Close

func (c *Client) Close()

CloseCacheConn closes the redis connection NOTE: this function should be ran as soon as the server is initialized

`defer s.Close()`

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, key string) error

Delete deletes a value from the cache

func (*Client) Exists added in v1.0.8

func (c *Client) Exists(ctx context.Context, key string) (bool, error)

Get reads a value from the cache

func (*Client) Get

func (c *Client) Get(ctx context.Context, key string) ([]byte, error)

Get reads a value from the cache

func (*Client) GetMany

func (c *Client) GetMany(ctx context.Context, keys []string) ([][]byte, error)

GetManyFromCache reads a value from the cache

func (*Client) Validate

func (c *Client) Validate() error

Validate validates the configuration of the Redis client.

func (*Client) Write

func (c *Client) Write(ctx context.Context, key string, value []byte) error

WriteToCache writes a value to the cache

func (*Client) WriteAny

func (c *Client) WriteAny(ctx context.Context, key string, value interface{}) error

WriteAny writes a value to the cache

func (*Client) WriteMany

func (c *Client) WriteMany(ctx context.Context, pairs map[string][]byte) error

WriteMany writes a many values to the cache

type DatastoreTxName

type DatastoreTxName string
const (
	// Defining a constant named `RedisWriteToCacheTxn` of type `DatastoreTxName` and assigning it the
	// value `"txn.redis.write-to-cache"`. This constant is used as a transaction name or identifier for
	// write operations on a Redis cache in a larger codebase.
	RedisWriteToCacheTxn DatastoreTxName = "txn.redis.write-to-cache"
	// `RedisReadFromCacheTxn` of type
	// `DatastoreTxName` and assigning it the value `"txn.redis.read-from-cache"`. This constant is
	// used as a transaction name or identifier for read operations on a Redis cache in a larger codebase.
	RedisReadFromCacheTxn DatastoreTxName = "txn.redis.read-from-cache"
	// Defining a constant named `RedisReadManyFromCacheTxn` of type `DatastoreTxName` and assigning it the
	// value `"txn.redis.read-many-from-cache"`. This constant is used as a transaction name or identifier
	// for read operations on multiple keys from a Redis cache in a larger codebase.
	RedisReadManyFromCacheTxn DatastoreTxName = "txn.redis.read-many-from-cache"
	// Defining a constant named `RedisDeleteFromCacheTxn` of type `DatastoreTxName` and assigning it the
	// value `"txn.redis.delete-from-cache"`. This constant is used as a transaction name or identifier for
	// delete operations on a Redis cache in a larger codebase.
	RedisDeleteFromCacheTxn DatastoreTxName = "txn.redis.delete-from-cache"
)

func (DatastoreTxName) String

func (d DatastoreTxName) String() string

String is a method defined on the `DatastoreTxName` type. It returns a string representation of the `DatastoreTxName` value. This method is used to convert the `DatastoreTxName` value to a string when it needs to be printed or displayed.

type Option

type Option func(*Client)

Option configures the redis client properly

func WithCacheTTLInSeconds

func WithCacheTTLInSeconds(cacheTTLInSeconds int) Option

WithCacheTTLInSeconds sets the cache TTL in seconds for the Redis client.

func WithLogger

func WithLogger(logger *zap.Logger) Option

WithLogger sets the logger for the Redis client.

func WithServiceName

func WithServiceName(serviceName string) Option

WithServiceName sets the service name for the Redis client.

func WithTelemetrySdk

func WithTelemetrySdk(sdk *instrumentation.Client) Option

WithTelemetrySdk sets the telemetry SDK for the Redis client.

func WithTlsEnabled added in v1.0.6

func WithTlsEnabled(enabled bool) Option

func WithURI

func WithURI(uri string) Option

WithURI sets the URI for the Redis client.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL