Documentation
¶
Index ¶
- type CacheKey
- type Client
- func (s *Client) DeleteFromCache(ctx context.Context, key string) error
- func (s *Client) GetFromCache(ctx context.Context, key string) ([]byte, error)
- func (s *Client) GetManyFromCache(ctx context.Context, keys []string) ([][]byte, error)
- func (c *Client) Validate() error
- func (s *Client) WriteAnyToCache(ctx context.Context, key string, value interface{}) error
- func (s *Client) WriteManyToCache(ctx context.Context, pairs map[string][]byte) error
- func (s *Client) WriteToCache(ctx context.Context, key string, value []byte) error
- func (s *Client) WriteToCacheWithTTL(ctx context.Context, key string, value []byte, timeToLiveInSeconds int) error
- type Option
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CacheKey ¶
type CacheKey string
func NewCacheKey ¶
NewCacheKey creates a new CacheKey with the given key.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client implements a Redis cache client with connection pooling and instrumentation support. It automatically handles connection management, key prefixing, and tracing of Redis operations.
func New ¶
New creates a new Redis cache client with the provided options. Example usage:
client, err := cacher.New(
cacher.WithLogger(logger),
cacher.WithRedisConn(pool),
cacher.WithServiceName("myservice"),
cacher.WithCacheTTLInSeconds(3600),
)
func (*Client) DeleteFromCache ¶
DeleteFromCache removes a value from the cache. It's safe to delete non-existent keys. Example usage:
err := client.DeleteFromCache(ctx, "user:123")
func (*Client) GetFromCache ¶
GetFromCache retrieves a value from the cache by key. Returns nil and an error if the key doesn't exist. Example usage:
data, err := client.GetFromCache(ctx, "user:123")
if err != nil {
if err == redis.ErrNil {
// Handle cache miss
}
return err
}
func (*Client) GetManyFromCache ¶
GetManyFromCache retrieves multiple values from the cache in a single operation. If any key is missing, it returns an error. For partial success/failure handling, use individual GetFromCache calls. Example usage:
keys := []string{"user:123", "user:456"}
values, err := client.GetManyFromCache(ctx, keys)
func (*Client) Validate ¶
Validate checks that all required fields are properly configured. It returns an error if any required configuration is missing or invalid.
Required configurations: - Redis connection pool - Logger - Service name - Cache TTL > 0
The instrumentation client is optional - a warning is logged if not provided.
func (*Client) WriteAnyToCache ¶
WriteAnyToCache marshals any JSON-serializable value and writes it to the cache. This is a convenience wrapper around WriteToCache with JSON marshaling. Example usage:
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
user := User{Name: "John", Age: 30}
err := client.WriteAnyToCache(ctx, "user:123", user)
func (*Client) WriteManyToCache ¶
WriteManyToCache writes multiple key-value pairs to the cache atomically. This is more efficient than multiple individual writes for bulk operations. Example usage:
pairs := map[string][]byte{
"user:123": []byte(`{"name":"John"}`),
"user:456": []byte(`{"name":"Jane"}`),
}
err := client.WriteManyToCache(ctx, pairs)
func (*Client) WriteToCache ¶
WriteToCache writes a value to the cache with the configured TTL. The key will be automatically prefixed with the service name. Example usage:
err := client.WriteToCache(ctx, "user:123", []byte(`{"name":"John"}`))
func (*Client) WriteToCacheWithTTL ¶ added in v1.20.0
func (s *Client) WriteToCacheWithTTL(ctx context.Context, key string, value []byte, timeToLiveInSeconds int) error
WriteToCacheWithTTL writes a value to the cache with a custom TTL. If timeToLiveInSeconds is <= 0, defaults to 60 seconds. Example usage:
// Cache for 5 minutes err := client.WriteToCacheWithTTL(ctx, "temp:123", data, 300)
type Option ¶
type Option func(*Client)
Option defines a function type that configures a Client. Options are used with New() to configure the client instance.
func WithCacheTTLInSeconds ¶
WithCacheTTLInSeconds sets the default time-to-live for cache entries in seconds. This TTL is used for all cache writes unless overridden by WriteToCacheWithTTL.
Example:
// Set default TTL to 1 hour
client, err := cacher.New(
cacher.WithCacheTTLInSeconds(3600),
)
func WithIntrumentationClient ¶
func WithIntrumentationClient(client *instrumentation.Client) Option
WithIntrumentationClient enables distributed tracing for cache operations. When configured, each cache operation will create a trace span for monitoring.
Example:
instrClient := instrumentation.NewClient()
client, err := cacher.New(
cacher.WithIntrumentationClient(instrClient),
)
func WithLogger ¶
WithLogger configures the logging instance for the cache client. The logger is used to record operational events and errors.
Example:
logger := zap.NewProduction()
client, err := cacher.New(
cacher.WithLogger(logger),
)
func WithRedisConn ¶
WithRedisConn configures the Redis connection pool. The pool manages a set of Redis connections for optimal performance.
Example:
pool := &redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp", "localhost:6379")
},
}
client, err := cacher.New(
cacher.WithRedisConn(pool),
)
func WithServiceName ¶
WithServiceName sets the service name used for key prefixing. The service name is prepended to all cache keys to prevent collisions when multiple services share the same Redis instance.
Example:
client, err := cacher.New(
cacher.WithServiceName("user-service"),
)