Files
VLoop/backend/internal/middleware/redis/redis.go
huanghaosheng 5d05c147ed style(backend): 精简 P1-1 期间的说明性注释
代码只留一行不变量。进程分工的动机、退避与重连的细节、测试可验证性的理由,都已在 docs/solutions/P1-1-async-workers-out-of-api.md 里写过,注释不再复述。

保留的是读代码看不出来的约束:超时派生自 poller 的 ctx、坏消息不能打断订阅、SSE 响应永不结束、订阅存活够久要重置退避。

文档补一句退避重置规则。这是删掉的注释里唯一没有落在文档上的细节。

验证:go test -count=1 ./... 全绿。
2026-11-08 15:47:10 +08:00

138 lines
3.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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
}
// 频道名由调用方用 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()
}