package redis import ( "context" "crypto/rand" "encoding/hex" "errors" "feedsystem_video_go/internal/config" "fmt" "strconv" "time" redis "github.com/redis/go-redis/v9" ) type Client struct { rdb *redis.Client keyPrefix string } const defaultKeyPrefix = "v1:" func NewClient(rdb *redis.Client, keyPrefix string) *Client { return &Client{rdb: rdb, keyPrefix: keyPrefix} } func NewFromEnv(cfg *config.RedisConfig) (*Client, error) { rdb := redis.NewClient(&redis.Options{ Addr: cfg.Host + ":" + strconv.Itoa(cfg.Port), Password: cfg.Password, DB: cfg.DB, }) return &Client{rdb: rdb, keyPrefix: defaultKeyPrefix}, nil } func (c *Client) Close() error { if c == nil || c.rdb == nil { return nil } return c.rdb.Close() } func (c *Client) Ping(ctx context.Context) error { if c == nil || c.rdb == nil { return errors.New("redis client not initialized") } return c.rdb.Ping(ctx).Err() } func IsMiss(err error) bool { return err == redis.Nil } func (c *Client) Key(format string, args ...any) string { prefix := "" if c != nil { prefix = c.keyPrefix } return prefix + fmt.Sprintf(format, args...) } func randToken(n int) (string, error) { b := make([]byte, n) if _, err := rand.Read(b); err != nil { return "", err } return hex.EncodeToString(b), nil } func (c *Client) Lock(ctx context.Context, key string, ttl time.Duration) (token string, ok bool, err error) { if c == nil || c.rdb == nil { return "", false, nil } token, err = randToken(16) if err != nil { return "", false, err } ok, err = c.rdb.SetNX(ctx, key, token, ttl).Result() return token, ok, err } var unlockScript = redis.NewScript(` if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) else return 0 end `) var incrementWithExpireScript = redis.NewScript(` local count = redis.call("INCR", KEYS[1]) if count == 1 then redis.call("PEXPIRE", KEYS[1], ARGV[1]) end return count `) func (c *Client) Unlock(ctx context.Context, key string, token string) error { if c == nil || c.rdb == nil { return nil } _, err := unlockScript.Run(ctx, c.rdb, []string{key}, token).Result() return err } // Publish 向频道发布一条消息。频道名由调用方用 Key 统一加前缀, // 同一 Redis 上的多套环境才不会互相收到对方的消息。 func (c *Client) Publish(ctx context.Context, channel string, payload []byte) error { if c == nil || c.rdb == nil { return errors.New("redis client not initialized") } return c.rdb.Publish(ctx, channel, payload).Err() } // Subscribe 订阅频道,并在返回前等到 broker 确认订阅生效: // 否则"订阅建立"与"第一条消息到达"之间有一个静默丢消息的窗口。 // 返回的 PubSub 由调用方负责 Close。 func (c *Client) Subscribe(ctx context.Context, channel string) (*redis.PubSub, error) { if c == nil || c.rdb == nil { return nil, errors.New("redis client not initialized") } ps := c.rdb.Subscribe(ctx, channel) if _, err := ps.Receive(ctx); err != nil { _ = ps.Close() return nil, err } return ps, nil } func (c *Client) IncrementWithExpire(ctx context.Context, key string, expire time.Duration) (int64, error) { if c == nil || c.rdb == nil { return 0, nil } return incrementWithExpireScript.Run( ctx, c.rdb, []string{key}, expire.Milliseconds(), ).Int64() }