2026-04-02 00:31:28 +08:00
|
|
|
package cache
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"errors"
|
|
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
goredis "github.com/redis/go-redis/v9"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type redisCache struct {
|
|
|
|
|
client *goredis.Client
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func newRedisCache(client *goredis.Client) Cache {
|
|
|
|
|
return &redisCache{client: client}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (c *redisCache) Get(ctx context.Context, key string) ([]byte, error) {
|
|
|
|
|
val, err := c.client.Get(ctx, key).Bytes()
|
|
|
|
|
if errors.Is(err, goredis.Nil) {
|
|
|
|
|
return nil, ErrNotFound
|
|
|
|
|
}
|
|
|
|
|
return val, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (c *redisCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
|
|
|
|
|
return c.client.Set(ctx, key, value, ttl).Err()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (c *redisCache) Delete(ctx context.Context, key string) error {
|
|
|
|
|
return c.client.Del(ctx, key).Err()
|
|
|
|
|
}
|
2026-04-15 16:11:05 +08:00
|
|
|
|
|
|
|
|
func (c *redisCache) DeletePrefix(ctx context.Context, prefix string) error {
|
|
|
|
|
if prefix == "" {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pattern := prefix + "*"
|
|
|
|
|
var cursor uint64
|
|
|
|
|
for {
|
|
|
|
|
keys, nextCursor, err := c.client.Scan(ctx, cursor, pattern, 100).Result()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
if len(keys) > 0 {
|
|
|
|
|
if err := c.client.Del(ctx, keys...).Err(); err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
cursor = nextCursor
|
|
|
|
|
if cursor == 0 {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|