Help us shape the future of Go! Take the 2026 Go Developer Survey

redis

package
v1.19.0 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: Apache-2.0 Imports: 32 Imported by: 6

Documentation

Index

Constants

View Source
const (
	ClusterType = "cluster"
	NodeType    = "node"
)

Variables

This section is empty.

Functions

func ClientHasJSONSupport

func ClientHasJSONSupport(c RedisClient) bool

func GetConnectedSlaves

func GetConnectedSlaves(ctx context.Context, c RedisClient) (int, error)

GetConnectedSlaves returns the number of slaves connected to the Redis master.

func GetServerVersion

func GetServerVersion(c RedisClient) (string, error)

func ParseClientFromProperties

func ParseClientFromProperties(properties map[string]string, componentType metadata.ComponentType, ctx context.Context, logger *kitlogger.Logger) (RedisClient, *Settings, error)

func StartOIDCTokenRefreshBackgroundRoutine added in v1.19.0

func StartOIDCTokenRefreshBackgroundRoutine(client RedisClient, username string, nextExpiration time.Time, tokenSource *OAuthTokenSourcePrivateKeyJWT, logger *kitlogger.Logger)

StartOIDCTokenRefreshBackgroundRoutine refreshes the OIDC access token before it expires and re-authenticates the live Redis connection pool with it.

Types

type ConfigurationSubscribeArgs

type ConfigurationSubscribeArgs struct {
	HandleSubscribedChange func(ctx context.Context, req *configuration.SubscribeRequest, handler configuration.UpdateHandler, channel string, id string)
	Req                    *configuration.SubscribeRequest
	Handler                configuration.UpdateHandler
	RedisChannel           string
	IsAllKeysChannel       bool
	ID                     string
}

type Duration

type Duration time.Duration

func (*Duration) DecodeString

func (r *Duration) DecodeString(value string) error

type OAuthTokenSourcePrivateKeyJWT added in v1.19.0

type OAuthTokenSourcePrivateKeyJWT struct {
	TokenEndpoint       oauth2.Endpoint
	ClientID            string
	Scopes              []string
	ClientAssertionCert string
	ClientAssertionKey  string
	Resource            string
	Audience            string
	Kid                 string
	// contains filtered or unexported fields
}

OAuthTokenSourcePrivateKeyJWT obtains OAuth2 access tokens using the client_credentials grant with the private_key_jwt client authentication method (RFC 7523), where the client authenticates to the token endpoint with a signed JWT assertion instead of a client secret. It is a port of the Kafka component's implementation in common/component/kafka/sasl_oauthbearer_private_key_jwt.go, without the Sarama-specific wrapping.

func (*OAuthTokenSourcePrivateKeyJWT) ForceToken added in v1.19.0

ForceToken discards any cached token and fetches a fresh one. It is used by the refresh routine, which runs before the cached token expires and would otherwise be handed the still-valid cached token back.

func (*OAuthTokenSourcePrivateKeyJWT) Token added in v1.19.0

Token returns the cached access token if it is still valid, otherwise it fetches a new one from the token endpoint.

type RedisClient

type RedisClient interface {
	IsNilValueError(error) bool
	Context() context.Context
	DoRead(ctx context.Context, args ...interface{}) (interface{}, error)
	DoWrite(ctx context.Context, args ...interface{}) error
	Del(ctx context.Context, keys ...string) error
	Get(ctx context.Context, key string) (string, error)
	GetDel(ctx context.Context, key string) (string, error)
	Close() error
	PingResult(ctx context.Context) (string, error)
	ConfigurationSubscribe(ctx context.Context, args *ConfigurationSubscribeArgs)
	SetNX(ctx context.Context, key string, value interface{}, expiration time.Duration) (*bool, error)
	EvalInt(ctx context.Context, script string, keys []string, args ...interface{}) (*int, error, error)
	XAdd(ctx context.Context, stream string, maxLenApprox int64, streamTTL string, values map[string]interface{}) (string, error)
	XGroupCreateMkStream(ctx context.Context, stream string, group string, start string) error
	XAck(ctx context.Context, stream string, group string, messageID string) error
	XReadGroupResult(ctx context.Context, group string, consumer string, streams []string, count int64, block time.Duration) ([]RedisXStream, error)
	XPendingExtResult(ctx context.Context, stream string, group string, start string, end string, count int64) ([]RedisXPendingExt, error)
	XClaimResult(ctx context.Context, stream string, group string, consumer string, minIdleTime time.Duration, messageIDs []string) ([]RedisXMessage, error)
	XClaimJustIDResult(ctx context.Context, stream string, group string, consumer string, minIdleTime time.Duration, messageIDs []string) ([]string, error)
	TxPipeline() RedisPipeliner
	TTLResult(ctx context.Context, key string) (time.Duration, error)
}

func ClientFromV8Client

func ClientFromV8Client(client v8.UniversalClient) RedisClient

type RedisError

type RedisError string

func (RedisError) Error

func (e RedisError) Error() string

func (RedisError) RedisError

func (RedisError) RedisError()

type RedisPipeliner

type RedisPipeliner interface {
	Exec(ctx context.Context) error
	Do(ctx context.Context, args ...interface{})
}

type RedisXMessage

type RedisXMessage struct {
	ID     string
	Values map[string]interface{}
}

type RedisXPendingExt

type RedisXPendingExt struct {
	ID         string
	Consumer   string
	Idle       time.Duration
	RetryCount int64
}

type RedisXStream

type RedisXStream struct {
	Stream   string
	Messages []RedisXMessage
}

type Settings

type Settings struct {
	// The Redis host
	Host string `mapstructure:"redisHost"`
	// The Redis port (optional, appended to Host if Host does not already contain a port)
	Port uint16 `mapstructure:"redisPort"`
	// The Redis password
	Password string `mapstructure:"redisPassword"`
	// The Redis username
	Username string `mapstructure:"redisUsername"`
	// The Redis Sentinel password
	SentinelPassword string `mapstructure:"sentinelPassword"`
	// The Redis Sentinel username
	SentinelUsername string `mapstructure:"sentinelUsername"`
	// Database to be selected after connecting to the server.
	DB int `mapstructure:"redisDB"`
	// The redis type node or cluster
	RedisType string `mapstructure:"redisType"`
	// Maximum number of retries before giving up.
	// A value of -1 (not 0) disables retries
	// Default is 3 retries
	RedisMaxRetries int `mapstructure:"redisMaxRetries"`
	// Minimum backoff between each retry.
	// Default is 8 milliseconds; -1 disables backoff.
	RedisMinRetryInterval Duration `mapstructure:"redisMinRetryInterval"`
	// Maximum backoff between each retry.
	// Default is 512 milliseconds; -1 disables backoff.
	RedisMaxRetryInterval Duration `mapstructure:"redisMaxRetryInterval"`
	// Dial timeout for establishing new connections.
	DialTimeout Duration `mapstructure:"dialTimeout"`
	// Timeout for socket reads. If reached, commands will fail
	// with a timeout instead of blocking. Use value -1 for no timeout and 0 for default.
	ReadTimeout Duration `mapstructure:"readTimeout"`
	// Timeout for socket writes. If reached, commands will fail
	WriteTimeout Duration `mapstructure:"writeTimeout"`
	// Maximum number of socket connections.
	PoolSize int `mapstructure:"poolSize"`
	// Minimum number of idle connections which is useful when establishing
	// new connection is slow.
	MinIdleConns int `mapstructure:"minIdleConns"`
	// Connection age at which client retires (closes) the connection.
	// Default is to not close aged connections.
	MaxConnAge Duration `mapstructure:"maxConnAge"`
	// Amount of time client waits for connection if all connections
	// are busy before returning an error.
	// Default is ReadTimeout + 1 second.
	PoolTimeout Duration `mapstructure:"poolTimeout"`
	// Amount of time after which client closes idle connections.
	// Should be less than server's timeout.
	// Default is 5 minutes. -1 disables idle timeout check.
	IdleTimeout Duration `mapstructure:"idleTimeout"`
	// Frequency of idle checks made by idle connections reaper.
	// Default is 1 minute. -1 disables idle connections reaper,
	// but idle connections are still discarded by the client
	// if IdleTimeout is set.
	IdleCheckFrequency Duration `mapstructure:"idleCheckFrequency"`
	// The master name
	SentinelMasterName string `mapstructure:"sentinelMasterName"`
	// Use Redis Sentinel for automatic failover.
	Failover bool `mapstructure:"failover"`

	// A flag to enable TLS for the Redis connection
	EnableTLS bool `mapstructure:"enableTLS"`

	// A flag to skip TLS certificate verification (insecure, use only for testing).
	// Defaults to false. When EnableTLS is true and this is false, proper certificate
	// verification is performed.
	InsecureSkipTLSVerify bool `mapstructure:"insecureSkipTLSVerify"`

	// Client certificate and key
	ClientCert string `mapstructure:"clientCert"`
	ClientKey  string `mapstructure:"clientKey"`

	// == state only properties ==
	TTLInSeconds *int   `mapstructure:"ttlInSeconds" mdonly:"state"`
	QueryIndexes string `mapstructure:"queryIndexes" mdonly:"state"`

	// == pubsub only properties ==
	// The consumer identifier
	ConsumerID string `mapstructure:"consumerID" mdonly:"pubsub"`
	// The interval between checking for pending messages to redelivery (0 disables redelivery)
	RedeliverInterval time.Duration `mapstructure:"redeliverInterval" mdonly:"pubsub"`
	// The amount time a message must be pending before attempting to redeliver it (0 disables redelivery)
	ProcessingTimeout time.Duration `mapstructure:"processingTimeout" mdonly:"pubsub"`
	// The size of the message queue for processing
	QueueDepth uint `mapstructure:"queueDepth" mdonly:"pubsub"`
	// The number of concurrent workers that are processing messages
	Concurrency uint `mapstructure:"concurrency" mdonly:"pubsub"`

	// The interval at which the component resets the idle time of the pending entries it
	// currently holds, so that they are not reclaimed while this consumer is still working on
	// them. Defaults to half of ProcessingTimeout; 0 disables the keep-alive.
	EntryKeepAliveInterval time.Duration `mapstructure:"entryKeepAliveInterval" mdonly:"pubsub"`

	// The max len of stream
	MaxLenApprox int64 `mapstructure:"maxLenApprox" mdonly:"pubsub"`

	// The TTL of stream entries
	StreamTTL time.Duration `mapstructure:"streamTTL" mdonly:"pubsub"`

	// EntraID / AzureAD Authentication based on the shared code which essentially uses the DefaultAzureCredential
	// from the official Azure Identity SDK for Go
	UseEntraID bool `mapstructure:"useEntraID" mapstructurealiases:"useAzureAD"`

	// OIDC private_key_jwt (RFC 7523) authentication: an OAuth2 access token is
	// obtained from the identity provider using a signed JWT client assertion,
	// and used as the password for the Redis AUTH command. The token is
	// refreshed in the background before it expires.
	UseOIDC bool `mapstructure:"useOIDC"`
	// URL of the OAuth2 identity provider access token endpoint
	OidcTokenEndpoint string `mapstructure:"oidcTokenEndpoint"`
	// The OAuth2 client ID that has been provisioned in the identity provider
	OidcClientID string `mapstructure:"oidcClientID"`
	// PEM-encoded X.509 certificate paired with the client assertion signing key
	OidcClientAssertionCert string `mapstructure:"oidcClientAssertionCert"`
	// PEM-encoded RSA private key used to sign the client assertion
	OidcClientAssertionKey string `mapstructure:"oidcClientAssertionKey"`
	// Optional OAuth2 resource parameter to include in the token request
	OidcResource string `mapstructure:"oidcResource"`
	// Optional override for the JWT client assertion audience (aud); defaults to the token endpoint URL
	OidcAudience string `mapstructure:"oidcAudience"`
	// Optional JWT key ID (kid) header for the client assertion
	OidcKid string `mapstructure:"oidcKid"`
	// Comma-delimited list of OAuth2/OIDC scopes to request with the access token; defaults to "openid"
	OidcScopes string `mapstructure:"oidcScopes"`
	// Optional PEM-encoded CA certificate used to verify the TLS connection to the token endpoint
	OidcCACert string `mapstructure:"oidcCACert"`
	// contains filtered or unexported fields
}

func (*Settings) Decode

func (s *Settings) Decode(in interface{}) error

func (*Settings) GetMinID added in v1.16.0

func (s *Settings) GetMinID(now time.Time) string

func (*Settings) GetOIDCTokenSource added in v1.19.0

func (s *Settings) GetOIDCTokenSource(ctx context.Context, logger *kitlogger.Logger) (*OAuthTokenSourcePrivateKeyJWT, time.Time, error)

GetOIDCTokenSource validates the OIDC private_key_jwt settings, builds the token source, fetches the initial access token and sets fetchToken so that each new connection authenticates with the current token. It returns the token source and the expiry of the initial token so a refresh routine can be scheduled.

func (*Settings) InitEntraID added in v1.17.10

func (s *Settings) InitEntraID(ctx context.Context, properties *map[string]string) (time.Time, error)

InitEntraID validates the Entra ID settings, uses the initial token's object ID as the ACL username, and sets fetchToken so that each new connection authenticates with a fresh token. It returns the initial token's expiry so a refresh routine can be scheduled.

func (*Settings) SetCertificate added in v1.14.0

func (s *Settings) SetCertificate(fn func(cert *tls.Certificate)) error

Jump to

Keyboard shortcuts

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