cache.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. package cache
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "time"
  7. "fwh-toolbox-server/cache/redisx"
  8. "github.com/redis/go-redis/v9"
  9. )
  10. func Init(addr string) {
  11. opt := redisx.Config{
  12. Addrs: []string{addr},
  13. DB: 12,
  14. }
  15. redisx.Init(&opt)
  16. }
  17. // ErrNotFound 用于表示缓存未命中
  18. var ErrNotFound = errors.New("cachex: not found")
  19. // helper: compute full key with prefix
  20. func fullKey(prefix, key string) string {
  21. if prefix == "" {
  22. return key
  23. }
  24. return fmt.Sprintf("%s:%s", prefix, key)
  25. }
  26. // RegisterHitHook / RegisterMissHook: 简单 hook,用户可利用来统计
  27. var (
  28. hitHook func(key string)
  29. missHook func(key string)
  30. )
  31. func RegisterHitHook(fn func(key string)) {
  32. hitHook = fn
  33. }
  34. func RegisterMissHook(fn func(key string)) {
  35. missHook = fn
  36. }
  37. // internal helpers to call hooks safely
  38. func onHit(key string) {
  39. if hitHook != nil {
  40. go func() { defer func() { recover() }(); hitHook(key) }()
  41. }
  42. }
  43. func onMiss(key string) {
  44. if missHook != nil {
  45. go func() { defer func() { recover() }(); missHook(key) }()
  46. }
  47. }
  48. /********* 字符串操作 *********/
  49. // Set string value
  50. func Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error {
  51. return redisx.Set(ctx, key, value, ttl)
  52. }
  53. // Get string value
  54. func Get(ctx context.Context, key string) (string, error) {
  55. val, err := redisx.Get(ctx, key)
  56. if err != nil {
  57. return "", err
  58. }
  59. return val, nil
  60. }
  61. func MSet(ctx context.Context, pairs ...interface{}) error {
  62. return redisx.MSet(ctx, pairs...)
  63. }
  64. func MGet(ctx context.Context, keys ...string) ([]interface{}, error) {
  65. return redisx.MGet(ctx, keys...)
  66. }
  67. func Incr(ctx context.Context, key string) (int64, error) {
  68. return redisx.Incr(ctx, key)
  69. }
  70. func Decr(ctx context.Context, key string) (int64, error) {
  71. return redisx.Decr(ctx, key)
  72. }
  73. /********* 哈希操作 *********/
  74. func HSet(ctx context.Context, key string, values ...interface{}) error {
  75. return redisx.HSet(ctx, key, values...)
  76. }
  77. func HGet(ctx context.Context, key, field string) (string, error) {
  78. return redisx.HGet(ctx, key, field)
  79. }
  80. func HGetAll(ctx context.Context, key string) (map[string]string, error) {
  81. return redisx.HGetAll(ctx, key)
  82. }
  83. /********* 列表操作 *********/
  84. func LLen(ctx context.Context, key string) (int64, error) {
  85. return redisx.LLen(ctx, key)
  86. }
  87. func LRange(ctx context.Context, key string, start, stop int64) ([]string, error) {
  88. return redisx.LRange(ctx, key, start, stop)
  89. }
  90. func LPush(ctx context.Context, key string, values ...interface{}) error {
  91. return redisx.LPush(ctx, key, values...)
  92. }
  93. func RPush(ctx context.Context, key string, values ...interface{}) error {
  94. return redisx.RPush(ctx, key, values...)
  95. }
  96. func LPop(ctx context.Context, key string) (string, error) {
  97. return redisx.LPop(ctx, key)
  98. }
  99. func LTrim(ctx context.Context, key string, start, stop int64) error {
  100. return redisx.LTrim(ctx, key, start, stop)
  101. }
  102. /********* 集合操作 *********/
  103. func SAdd(ctx context.Context, key string, members ...interface{}) error {
  104. return redisx.SAdd(ctx, key, members...)
  105. }
  106. func SRem(ctx context.Context, key string, members ...interface{}) error {
  107. return redisx.SRem(ctx, key, members...)
  108. }
  109. func SMembers(ctx context.Context, key string) ([]string, error) {
  110. return redisx.SMembers(ctx, key)
  111. }
  112. func SIsMember(ctx context.Context, key string, member interface{}) (bool, error) {
  113. return redisx.SIsMember(ctx, key, member)
  114. }
  115. /********* 有序集合操作 *********/
  116. func ZAdd(ctx context.Context, key string, members ...redis.Z) error {
  117. return redisx.ZAdd(ctx, key, members...)
  118. }
  119. func ZRange(ctx context.Context, key string, start, stop int64) ([]string, error) {
  120. return redisx.ZRange(ctx, key, start, stop)
  121. }
  122. /********* Stream(流)操作 *********/
  123. // 添加消息
  124. func XAdd(ctx context.Context, stream string, values map[string]interface{}) (string, error) {
  125. return redisx.XAdd(ctx, stream, values)
  126. }
  127. // 读取消息
  128. func XRead(ctx context.Context, streams map[string]string, count int64) ([]redis.XStream, error) {
  129. return redisx.XRead(ctx, streams, count)
  130. }
  131. // 创建消费者组
  132. func XGroupCreate(ctx context.Context, stream, group, start string) error {
  133. return redisx.XGroupCreate(ctx, stream, group, start)
  134. }
  135. // 从消费者组读取
  136. func XReadGroup(ctx context.Context, group, consumer string, streams map[string]string, count int64) ([]redis.XStream, error) {
  137. return redisx.XReadGroup(ctx, group, consumer, streams, count)
  138. }
  139. // 从消费者组读取滞留消息
  140. func XAutoClaim(ctx context.Context, stream string, group string, consumer string, idle time.Duration, count int64) (messages []redis.XMessage, start string, err error) {
  141. return redisx.XAutoClaim(ctx, stream, group, consumer, idle, count)
  142. }
  143. // 从消费者组读取指定ID的Pending状态信息
  144. func XPendingExtOne(ctx context.Context, stream string, group string, consumer string, id string) (*redis.XPendingExt, error) {
  145. return redisx.XPendingExtOne(ctx, stream, group, consumer, id)
  146. }
  147. // 确认消息
  148. func XAck(ctx context.Context, stream, group string, ids ...string) error {
  149. return redisx.XAck(ctx, stream, group, ids...)
  150. }
  151. // 确认同时删除消息
  152. func XAckDel(ctx context.Context, stream, group string, ids ...string) error {
  153. return redisx.XAckDel(ctx, stream, group, ids...)
  154. }
  155. // 查询范围内指定的消息信息
  156. func XRangeN(ctx context.Context, stream, start, stop string, count int64) ([]redis.XMessage, error) {
  157. return redisx.XRangeN(ctx, stream, start, stop, count)
  158. }
  159. // 获取完整的Stream信息
  160. func XInfoStreamFull(ctx context.Context, key string, count int) (*redis.XInfoStreamFull, error) {
  161. return redisx.XInfoStreamFull(ctx, key, count)
  162. }
  163. /********* 分布式锁操作 *********/
  164. type RedisLock = redisx.RedisLock
  165. func TryLock(ctx context.Context, key string, ttl time.Duration) (*RedisLock, bool, error) {
  166. return redisx.TryLock(ctx, key, ttl)
  167. }
  168. func Lock(ctx context.Context, key string, ttl, retryInterval, timeout time.Duration) (*RedisLock, error) {
  169. return redisx.Lock(ctx, key, ttl, retryInterval, timeout)
  170. }
  171. func LockRelease(ctx context.Context, key string, token string) error {
  172. return redisx.LockRelease(ctx, key, token)
  173. }
  174. /********* JSON操作 *********/
  175. // SetJSON 将任意结构体序列化为 JSON 存入 Redis
  176. func SetJSON(ctx context.Context, key string, value interface{}, ttl time.Duration) error {
  177. return redisx.SetJSON(ctx, key, value, ttl)
  178. }
  179. // GetJSON 从 Redis 获取并反序列化为指定结构体
  180. func GetJSON[T any](ctx context.Context, key string, dest *T) error {
  181. return redisx.GetJSON[T](ctx, key, dest)
  182. }
  183. // MustGetJSON 返回默认值版本(未命中时返回 nil)
  184. func MustGetJSON[T any](ctx context.Context, key string) *T {
  185. return redisx.MustGetJSON[T](ctx, key)
  186. }
  187. // HSetJSON 在 Hash 中存储 JSON
  188. func HSetJSON(ctx context.Context, key, field string, value interface{}) error {
  189. return redisx.HSetJSON(ctx, key, field, value)
  190. }
  191. // HGetJSON 从 Hash 中读取 JSON
  192. func HGetJSON[T any](ctx context.Context, key, field string, dest *T) error {
  193. return redisx.HGetJSON[T](ctx, key, field, dest)
  194. }
  195. // MGetJSON 支持批量获取多个 JSON 对象
  196. func MGetJSON[T any](ctx context.Context, keys ...string) (map[string]*T, []string, error) {
  197. return redisx.MGetJSON[T](ctx, keys...)
  198. }
  199. /********* Lua脚本操作 *********/
  200. func RunScript(ctx context.Context, script string, keys []string, args ...interface{}) (interface{}, error) {
  201. return redisx.RunScript(ctx, script, keys, args...)
  202. }
  203. /********* 发布订阅操作 *********/
  204. func Publish(ctx context.Context, channel string, msg interface{}) error {
  205. return redisx.Publish(ctx, channel, msg)
  206. }
  207. func Subscribe(ctx context.Context, channel string) *redis.PubSub {
  208. return redisx.Subscribe(ctx, channel)
  209. }
  210. /********* 管道与事务 *********/
  211. func Pipeline(ctx context.Context, fn func(redis.Pipeliner) error) ([]redis.Cmder, error) {
  212. return redisx.Pipeline(ctx, fn)
  213. }
  214. /********* 工具方法 *********/
  215. // Delete
  216. func Delete(ctx context.Context, keys ...string) error {
  217. return redisx.Del(ctx, keys...)
  218. }
  219. // Expire
  220. func Expire(ctx context.Context, key string, ttl time.Duration) (bool, error) {
  221. return redisx.Expire(ctx, key, ttl)
  222. }
  223. // ExpireAt
  224. func ExpireAt(ctx context.Context, key string, tm time.Time) (bool, error) {
  225. return redisx.ExpireAt(ctx, key, tm)
  226. }
  227. // TTL
  228. func TTL(ctx context.Context, key string) (time.Duration, error) {
  229. return redisx.TTL(ctx, key)
  230. }
  231. // Exists
  232. func Exists(ctx context.Context, key string) (bool, error) {
  233. return redisx.Exists(ctx, key)
  234. }