Files
VLoop/backend/internal/middleware/redis/cache.go
huanghaosheng c210e75996 style(backend): 清理幂等写入路径的注释
注释只保留一行级约束。
长段理由移入设计文档。
验证:go test -count=1 ./... 全绿。
2026-10-31 00:03:53 +08:00

56 lines
1.5 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"
"errors"
"time"
)
func (c *Client) GetBytes(ctx context.Context, key string) ([]byte, error) {
if c == nil || c.rdb == nil {
return nil, errors.New("redis client not initialized")
}
return c.rdb.Get(ctx, key).Bytes()
}
func (c *Client) SetBytes(ctx context.Context, key string, value []byte, ttl time.Duration) error {
if c == nil || c.rdb == nil {
return errors.New("redis client not initialized")
}
return c.rdb.Set(ctx, key, value, ttl).Err()
}
func (c *Client) Del(ctx context.Context, key string) error {
if c == nil || c.rdb == nil {
return errors.New("redis client not initialized")
}
return c.rdb.Del(ctx, key).Err()
}
// SetNX 仅在 key 不存在时写入;key 由调用方拼好。
// 失败必须返回 error,调用方据此判断占位是否生效。
func (c *Client) SetNX(ctx context.Context, key string, value []byte, ttl time.Duration) (bool, error) {
if c == nil || c.rdb == nil {
return false, errors.New("redis client not initialized")
}
return c.rdb.SetNX(ctx, key, value, ttl).Result()
}
func (c *Client) DelByPattern(ctx context.Context, pattern string) error {
if c == nil || c.rdb == nil {
return nil
}
iter := c.rdb.Scan(ctx, 0, pattern, 0).Iterator()
for iter.Next(ctx) {
_ = c.rdb.Del(ctx, iter.Val())
}
return iter.Err()
}
func (c *Client) MGet(cacheCtx context.Context, cacheKeys ...string) ([]interface{}, error) {
if c == nil || c.rdb == nil {
return nil, errors.New("redis client not initialized")
}
return c.rdb.MGet(cacheCtx, cacheKeys...).Result()
}