Documentation
¶
Index ¶
- Constants
- type Client
- func (c *Client) Close() error
- func (c *Client) CompareAndDelete(ctx context.Context, key string, expectedValue []byte) (bool, error)
- func (c *Client) CompareAndSet(ctx context.Context, key string, expectedValue, newValue []byte, ...) (bool, error)
- func (c *Client) Delete(ctx context.Context, key string) error
- func (c *Client) Get(ctx context.Context, key string) ([]byte, error)
- func (c *Client) GetOrSet(ctx context.Context, key string, value []byte, ttl time.Duration) (storedValue []byte, wasSet bool, err error)
- func (c *Client) Health(ctx context.Context) error
- func (c *Client) LoadTimeout() time.Duration
- func (c *Client) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
- func (c *Client) Stats() (map[string]any, error)
- type Config
- type TLSConfig
Constants ¶
const ( // ModeStandalone dials one server and speaks the single-node protocol. It is // the default, and the empty Mode means exactly this. ModeStandalone = "standalone" // ModeCluster speaks the cluster protocol against the single configured // address, which the client treats as a seed and follows the slot map from. // Required by endpoints that answer MOVED to a single-node client, such as // Amazon ElastiCache Serverless. ModeCluster = "cluster" )
Connection modes selecting which protocol the client speaks.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client implements the cache.Cache interface using Redis as the backend.
func NewClient ¶
NewClient creates a new Redis cache client. Validates configuration and establishes connection.
func (*Client) Close ¶
Close closes the Redis client and releases resources. After calling Close, the client should not be used. Subsequent calls to Close return cache.ErrClosed.
func (*Client) CompareAndDelete ¶ added in v0.59.0
func (c *Client) CompareAndDelete(ctx context.Context, key string, expectedValue []byte) (bool, error)
CompareAndDelete atomically removes a key only if its current value matches. Returns (deleted, error):
- deleted=true: this call removed the key (comparison matched)
- deleted=false: the key was not removed by this call
expectedValue must be non-nil: nil returns cache.ErrNilExpectedValue without a round trip, because go-redis writes a nil []byte as a zero-length bulk string that would silently compare against the empty string. An empty slice is a real comparison against the empty string, matching CompareAndSet.
deleted=false does not distinguish a failed comparison from a key that was already gone, so it never proves another holder's value is still present. Uses Lua script for atomicity.
func (*Client) CompareAndSet ¶
func (c *Client) CompareAndSet(ctx context.Context, key string, expectedValue, newValue []byte, ttl time.Duration) (bool, error)
CompareAndSet atomically compares and swaps a value. Returns (success, error):
- success=true: Value was updated (comparison matched)
- success=false: Value was NOT updated (comparison failed)
expectedValue=nil means "set only if key doesn't exist" (acquire lock). Any non-nil expectedValue — including an empty slice — is a real compare-and-swap, so an absent key fails the comparison. Uses Lua script for atomicity. A ttl of 0 stores the key without expiration; any positive ttl below 1ms is raised to 1ms, matching what go-redis does for Set and GetOrSet.
func (*Client) Delete ¶
Delete removes a key from the cache. Does not return error if key doesn't exist.
func (*Client) Get ¶
Get retrieves a value from the cache. Returns cache.ErrNotFound if the key doesn't exist.
func (*Client) GetOrSet ¶
func (c *Client) GetOrSet(ctx context.Context, key string, value []byte, ttl time.Duration) (storedValue []byte, wasSet bool, err error)
GetOrSet atomically gets an existing value or sets a new one. Returns (storedValue, wasSet, error):
- wasSet=true: Value was newly set (first-time processing)
- wasSet=false: Value already existed (duplicate detected)
- storedValue: Always returns the value in cache (current or newly set)
Uses Redis SET NX GET for atomicity, which requires Redis 7.0+.
func (*Client) Health ¶
Health checks if the Redis connection is healthy. Uses PING command to verify connectivity.
func (*Client) LoadTimeout ¶ added in v0.62.0
LoadTimeout reports the configured cache-leg bound for cache.LoadThrough, satisfying cache.LoadTimeoutProvider. It is per-instance, so each tenant's client carries its own cache.loadtimeout rather than a process-wide value.
func (*Client) Set ¶
Set stores a value in the cache with the specified TTL. TTL of 0 means no expiration (use with caution). Returns cache.ErrInvalidTTL if TTL is negative.
func (*Client) Stats ¶
Stats returns Redis server statistics. Includes metrics from Redis INFO command.
The "mode" entry says how to read the rest: under ModeCluster, INFO is answered by whichever single node the command was routed to, and the pool counters are the aggregate across every node's pool. Under ModeStandalone both describe the one server.
type Config ¶
type Config struct {
// Host is the Redis server hostname or IP address.
Host string `config:"host" required:"true"`
// Port is the Redis server port (default: 6379).
Port int `config:"port" default:"6379"`
// Mode selects the protocol the client speaks: ModeStandalone (the default,
// and what the empty string means) or ModeCluster. Cluster is required for a
// cluster-protocol endpoint such as Amazon ElastiCache Serverless, which
// answers MOVED to a single-node client. Under cluster, Database must be 0 —
// the cluster client has no database selection. Filled from
// config.RedisConfig, which owns the cache.redis.mode key (env
// CACHE_REDIS_MODE); deliberately carries no config: tag, because nothing
// injects this struct and the tags on the fields around it are dead (#1729).
Mode string
// Username is the Redis ACL user to authenticate as, sent as
// AUTH <username> <password>. Empty authenticates as the implicit "default"
// user. Requires Password — Validate refuses a name with an empty password,
// because the driver then sends no AUTH and the dial would run as the default
// user. Required by deployments that gate access with ACLs, such as Amazon
// ElastiCache RBAC. Filled from config.RedisConfig, which owns the
// cache.redis.username key (env CACHE_REDIS_USERNAME); deliberately carries
// no config: tag, because nothing injects this struct and the tags on the
// fields around it are dead (#1729).
Username string
// Password for Redis authentication (optional).
// Should be provided via environment variable: CACHE_REDIS_PASSWORD
Password string `config:"password"`
// Database number to use (default: 0).
// Redis supports databases 0-15 by default.
Database int `config:"database" default:"0"`
// PoolSize is the maximum number of socket connections (default: 10).
// Higher values allow more concurrent operations but consume more resources.
PoolSize int `config:"pool_size" default:"10"`
// DialTimeout is the timeout for establishing new connections (default: 5s).
DialTimeout time.Duration `config:"dial_timeout" default:"5s"`
// LoadTimeout bounds each cache leg of cache.LoadThrough (cache.loadtimeout).
// Zero leaves the helper on its own fallback; a deployment-resolved config always
// carries a positive value.
LoadTimeout time.Duration `config:"load_timeout" default:"500ms"`
// ReadTimeout is the timeout for socket reads (default: 3s).
// -1 disables timeout.
ReadTimeout time.Duration `config:"read_timeout" default:"3s"`
// WriteTimeout is the timeout for socket writes (default: 3s).
// -1 disables timeout.
WriteTimeout time.Duration `config:"write_timeout" default:"3s"`
// MaxRetries is the maximum number of retries before giving up (default: 3).
// -1 disables retries.
MaxRetries int `config:"max_retries" default:"3"`
// MinRetryBackoff is the minimum backoff between retries (default: 8ms).
MinRetryBackoff time.Duration `config:"min_retry_backoff" default:"8ms"`
// MaxRetryBackoff is the maximum backoff between retries (default: 512ms).
MaxRetryBackoff time.Duration `config:"max_retry_backoff" default:"512ms"`
// TLS configures the client-side TLS of the connection. Zero value =
// plaintext.
TLS TLSConfig `config:"tls"`
}
Config holds Redis-specific configuration options.
func (*Config) Validate ¶
Validate performs fail-fast validation of Redis configuration. Returns error if configuration is invalid.
One rule is a coupling rather than a range check: under ModeCluster a non-zero Database is refused, because go-redis drops UniversalOptions.DB when it builds the cluster client (UniversalOptions.Cluster copies no DB, and ClusterOptions has no such field). Accepting it would move a deployment's whole keyspace to database 0 on the mode flip alone, with nothing said.
type TLSConfig ¶ added in v0.65.0
type TLSConfig struct {
// Enabled turns TLS on. False with any other field set is refused.
Enabled bool `config:"enabled"`
// CAFile and CAValue name the root bundle that verifies the server.
CAFile string `config:"cafile"`
CAValue string `config:"cavalue"`
// CertFile and CertValue name the client certificate; a cert requires a key.
CertFile string `config:"certfile"`
CertValue string `config:"certvalue"`
// KeyFile and KeyValue name the client key; a key requires a cert.
KeyFile string `config:"keyfile"`
KeyValue string `config:"keyvalue"`
// ServerName overrides the SNI/verification hostname; empty defaults to Host.
ServerName string `config:"servername"`
// MinVersion: "" or "1.2" (default floor) | "1.3".
MinVersion string `config:"minversion"`
}
TLSConfig enables TLS on the Redis connection. Each PEM piece comes from a file path (*File) or a base64-encoded PEM string (*Value) — at most one source per piece. An enabled block with no material at all verifies against the system roots; staged material under a disabled block is an error, not a warning, because a silently plaintext cache connection is the failure mode this config exists to prevent.