Documentation
¶
Index ¶
- Variables
- func EnsureKeysInSameSlot(keys []string, hashTag string) []string
- func ExecuteReadPipeline(ctx context.Context, fn PipelineFunc) ([]redis.Cmder, error)
- func ExecuteScript(ctx context.Context, scriptName, scriptContent string, keys []string, ...) (interface{}, error)
- func ExecuteWritePipeline(ctx context.Context, fn PipelineFunc) ([]redis.Cmder, error)
- func IsClusterClient(client redis.UniversalClient) bool
- func RedisTLSOptions(tlsCfg *config.TLS) *tls.Config
- func UpdateRedisServerMetrics(ctx context.Context)
- func UploadAllScripts(ctx context.Context) error
- func UploadScript(ctx context.Context, scriptName, scriptContent string) (string, error)
- type Client
- type PipelineFunc
Constants ¶
This section is empty.
Variables ¶
var ( // ErrScriptNotFound is returned when a script is not found in the scripts map ErrScriptNotFound = errors.New("script not found") )
var LuaScripts = map[string]string{
"IncrementAndExpire": `
local count = redis.call("INCR", KEYS[1])
redis.call("EXPIRE", KEYS[1], ARGV[1])
return count
`,
"AddToSetAndExpire": `
local result = redis.call("SADD", KEYS[1], ARGV[1])
redis.call("EXPIRE", KEYS[1], ARGV[2])
return result
`,
"ZAddCountAndExpire": `
redis.call("ZADD", KEYS[1], ARGV[1], ARGV[2])
local count = redis.call("ZCOUNT", KEYS[1], "-inf", "+inf")
redis.call("EXPIRE", KEYS[1], ARGV[4])
redis.call("HSET", KEYS[2], ARGV[3], count)
redis.call("EXPIRE", KEYS[2], ARGV[4])
return count
`,
"CalculateAdaptiveToleration": `
local positive = tonumber(redis.call("HGET", KEYS[1], "positive") or "0")
local negative = tonumber(redis.call("HGET", KEYS[1], "negative") or "0")
local min_percent = tonumber(ARGV[1])
local max_percent = tonumber(ARGV[2])
local scale_factor = tonumber(ARGV[3])
local static_percent = tonumber(ARGV[4])
local adaptive_enabled = tonumber(ARGV[5]) == 1
-- If adaptive toleration is disabled or there are no positive attempts, use static percentage
if not adaptive_enabled or positive == 0 then
local max_negative = math.floor((static_percent * positive) / 100)
return {static_percent, max_negative, positive, negative, 0}
end
-- Calculate adaptive percentage based on positive attempts and scale factor
local percent = min_percent
if positive > 0 then
-- Calculate percentage between min and max based on positive attempts and scale factor
local factor = math.min(1, math.log(positive + 1) / math.log(100) * scale_factor)
percent = math.floor(min_percent + (max_percent - min_percent) * factor)
-- Ensure percent is within bounds
percent = math.max(min_percent, math.min(max_percent, percent))
end
-- Calculate maximum allowed negative attempts
local max_negative = math.floor((percent * positive) / 100)
-- Return the calculated percentage, max negative attempts, positive count, positive count, and factor
return {percent, max_negative, positive, negative, 1}
`,
"RWPAllowSet": `
local key = KEYS[1]
local threshold = tonumber(ARGV[1])
local ttl = tonumber(ARGV[2])
local hash = ARGV[3]
if redis.call('SISMEMBER', key, hash) == 1 then
redis.call('EXPIRE', key, ttl)
return 1
end
local card = redis.call('SCARD', key)
if card < threshold then
redis.call('SADD', key, hash)
redis.call('EXPIRE', key, ttl)
return 1
end
return 0
`,
"ColdStartGraceSeed": `
local c = redis.call('SET', KEYS[1], '1', 'NX', 'EX', ARGV[1])
redis.call('SET', KEYS[2], '1', 'NX', 'EX', ARGV[1])
if c then return 1 else return 0 end
`,
"UnlockIfTokenMatches": `
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end
`,
}
LuaScripts contains all the Lua scripts used in the application
Functions ¶
func EnsureKeysInSameSlot ¶ added in v1.7.7
EnsureKeysInSameSlot ensures that all keys hash to the same slot in Redis Cluster by adding a common hash tag if needed (exported version) The hashTag parameter allows specifying a custom hash tag to use
func ExecuteReadPipeline ¶ added in v1.7.1
ExecuteReadPipeline executes multiple Redis read commands in a pipeline to reduce network round trips. It takes a context and a function that defines the commands to execute. The function should add commands to the pipeline but not execute them. Returns the command results and any error that occurred.
func ExecuteScript ¶ added in v1.7.7
func ExecuteScript(ctx context.Context, scriptName, scriptContent string, keys []string, args ...interface{}) (interface{}, error)
ExecuteScript executes a Lua script on Redis using its SHA1 hash. If the script is not found or Redis returns NOSCRIPT, it attempts to re-upload the script. This function is thread-safe and can be called concurrently.
If scriptContent is empty and the script is not found in the local cache, ErrScriptNotFound is returned. This allows callers to handle the case where a script needs to be uploaded first.
In Redis Cluster mode, this function ensures that all keys hash to the same slot by adding a common hash tag if needed.
func ExecuteWritePipeline ¶ added in v1.7.1
ExecuteWritePipeline executes multiple Redis write commands in a pipeline to reduce network round trips. It takes a context and a function that defines the commands to execute. The function should add commands to the pipeline but not execute them. Returns the command results and any error that occurred.
func IsClusterClient ¶ added in v1.7.7
func IsClusterClient(client redis.UniversalClient) bool
IsClusterClient checks if the Redis client is a cluster client (exported version)
func RedisTLSOptions ¶ added in v1.3.2
RedisTLSOptions checks if Redis TLS is enabled in the configuration. If TLS is enabled, it loads the X509 key pair and creates a tls.Config object. The loaded certificate is added to the tls.Config object. If an error occurs while loading the key pair, it logs the error and returns nil. If Redis TLS is disabled, it returns nil.
func UpdateRedisServerMetrics ¶ added in v1.7.3
UpdateRedisServerMetrics periodically collects and updates Redis server metrics
func UploadAllScripts ¶ added in v1.7.7
UploadAllScripts uploads all Lua scripts defined in lua_scripts.go to Redis. This function should be called at program startup to ensure all scripts are available.
func UploadScript ¶ added in v1.7.7
UploadScript uploads a Lua script to Redis and stores its SHA1 hash. If the script is already uploaded, it returns the existing SHA1 hash. This function is thread-safe and can be called concurrently.
Types ¶
type Client ¶ added in v1.4.10
type Client interface {
// GetWriteHandle retrieves the Redis client's write handle for operations requiring write access.
GetWriteHandle() redis.UniversalClient
// GetReadHandle retrieves a Redis client's read handle, supporting multiple read handles for load balancing.
GetReadHandle() redis.UniversalClient
// GetWritePipeline returns a Redis pipeline for batching write operations.
GetWritePipeline() redis.Pipeliner
// GetReadPipeline returns a Redis pipeline for batching read operations.
GetReadPipeline() redis.Pipeliner
// Close releases all resources associated with the client, including write and read handles, and closes any open connections.
Close()
}
Client defines an interface for interacting with a Redis client with methods for initialization and handle retrieval.
func NewClient ¶ added in v1.4.10
func NewClient() Client
NewClient creates and returns a new instance of a Redis client that implements the Client interface.
func NewTestClient ¶ added in v1.4.10
NewTestClient initializes and returns a new testClient instance, implementing the Client interface using the provided Redis client.
type PipelineFunc ¶ added in v1.7.1
PipelineFunc is a function that executes Redis commands on a pipeline.