fixed blocking important issues

This commit is contained in:
Mazyar
2026-05-30 12:29:45 +03:30
parent bb221f3cda
commit ad702f24bf
14 changed files with 174 additions and 72 deletions
+23 -12
View File
@@ -23,8 +23,7 @@ type Config struct {
type Client interface {
Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error
Get(ctx context.Context, key string) (string, error)
Incr(ctx context.Context, key string) (int64, error)
Expire(ctx context.Context, key string, expiration time.Duration) error
IncrWithExpire(ctx context.Context, key string, expiration time.Duration) (int64, error)
Del(ctx context.Context, keys ...string) error
Exists(ctx context.Context, keys ...string) (int64, error)
Close() error
@@ -72,6 +71,28 @@ func NewClient(config *Config, logger logger.Logger) (Client, error) {
return &client{rdb: rdb}, nil
}
const incrWithExpireScript = `
local current = redis.call("INCR", KEYS[1])
if current == 1 then
redis.call("EXPIRE", KEYS[1], ARGV[1])
else
local ttl = redis.call("TTL", KEYS[1])
if ttl == -1 then
redis.call("EXPIRE", KEYS[1], ARGV[1])
end
end
return current
`
// IncrWithExpire atomically increments a counter and ensures the key has a TTL.
func (c *client) IncrWithExpire(ctx context.Context, key string, expiration time.Duration) (int64, error) {
seconds := int64(expiration.Seconds())
if seconds < 1 {
seconds = 1
}
return c.rdb.Eval(ctx, incrWithExpireScript, []string{key}, seconds).Int64()
}
// Set sets a key-value pair with expiration
func (c *client) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error {
return c.rdb.Set(ctx, key, value, expiration).Err()
@@ -82,16 +103,6 @@ func (c *client) Get(ctx context.Context, key string) (string, error) {
return c.rdb.Get(ctx, key).Result()
}
// Incr increments a key's integer value.
func (c *client) Incr(ctx context.Context, key string) (int64, error) {
return c.rdb.Incr(ctx, key).Result()
}
// Expire sets a timeout on a key.
func (c *client) Expire(ctx context.Context, key string, expiration time.Duration) error {
return c.rdb.Expire(ctx, key, expiration).Err()
}
// Del deletes one or more keys
func (c *client) Del(ctx context.Context, keys ...string) error {
return c.rdb.Del(ctx, keys...).Err()