standalone_redis.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. package redis
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "github.com/go-redis/redis/v8"
  8. "strconv"
  9. "time"
  10. )
  11. // StandaloneRedisClient
  12. // @Description: 单机redis客户端
  13. type StandaloneRedisClient struct {
  14. redisClient *redis.Client
  15. }
  16. func InitStandaloneRedis(config string) (standaloneRedis StandaloneRedisClient, err error) {
  17. var cf map[string]string
  18. err = json.Unmarshal([]byte(config), &cf)
  19. if err != nil {
  20. return
  21. }
  22. //if _, ok := cf["key"]; !ok {
  23. // cf["key"] = DefaultKey
  24. //}
  25. if _, ok := cf["conn"]; !ok {
  26. err = errors.New("config has no conn key")
  27. return
  28. }
  29. // db库
  30. dbNum := 0
  31. // 如果指定了db库
  32. if _, ok := cf["dbNum"]; ok {
  33. dbNum, err = strconv.Atoi(cf["dbNum"])
  34. if err != nil {
  35. return
  36. }
  37. }
  38. // 密码
  39. if _, ok := cf["password"]; !ok {
  40. cf["password"] = ""
  41. }
  42. client := redis.NewClient(&redis.Options{
  43. Addr: cf["conn"],
  44. Password: cf["password"],
  45. DB: dbNum,
  46. //PoolSize: 10, //连接池最大socket连接数,默认为10倍CPU数, 10 * runtime.NumCPU(暂不配置)
  47. })
  48. _, err = client.Ping(context.TODO()).Result()
  49. if err != nil {
  50. err = errors.New("redis 链接失败:" + err.Error())
  51. return
  52. }
  53. standaloneRedis = StandaloneRedisClient{redisClient: client}
  54. return
  55. }
  56. // Get cache from redis.
  57. func (rc StandaloneRedisClient) Get(key string) interface{} {
  58. data, err := rc.redisClient.Get(context.TODO(), key).Bytes()
  59. if err != nil {
  60. return nil
  61. }
  62. return data
  63. }
  64. func (rc StandaloneRedisClient) RedisBytes(key string) (data []byte, err error) {
  65. data, err = rc.redisClient.Get(context.TODO(), key).Bytes()
  66. return
  67. }
  68. func (rc StandaloneRedisClient) RedisString(key string) (data string, err error) {
  69. data, err = rc.redisClient.Get(context.TODO(), key).Result()
  70. return
  71. }
  72. func (rc StandaloneRedisClient) RedisInt(key string) (data int, err error) {
  73. data, err = rc.redisClient.Get(context.TODO(), key).Int()
  74. return
  75. }
  76. // Put put cache to redis.
  77. func (rc StandaloneRedisClient) Put(key string, val interface{}, timeout time.Duration) error {
  78. var err error
  79. err = rc.redisClient.SetEX(context.TODO(), key, val, timeout).Err()
  80. if err != nil {
  81. return err
  82. }
  83. err = rc.redisClient.HSet(context.TODO(), DefaultKey, key, true).Err()
  84. return err
  85. }
  86. func (rc StandaloneRedisClient) SetNX(key string, val interface{}, timeout time.Duration) bool {
  87. result, err := rc.redisClient.SetEX(context.TODO(), key, val, timeout).Result()
  88. if err != nil || result != "OK" {
  89. return false
  90. }
  91. return true
  92. }
  93. // Delete delete cache in redis.
  94. func (rc StandaloneRedisClient) Delete(key string) error {
  95. var err error
  96. err = rc.redisClient.Del(context.TODO(), key).Err()
  97. if err != nil {
  98. return err
  99. }
  100. err = rc.redisClient.HDel(context.TODO(), DefaultKey, key).Err()
  101. return err
  102. }
  103. // IsExist check cache's existence in redis.
  104. func (rc StandaloneRedisClient) IsExist(key string) bool {
  105. result, err := rc.redisClient.Exists(context.TODO(), key).Result()
  106. if err != nil {
  107. return false
  108. }
  109. if result == 0 {
  110. err = rc.redisClient.HDel(context.TODO(), DefaultKey, key).Err()
  111. if err != nil {
  112. return false
  113. }
  114. }
  115. return true
  116. }
  117. // Put put cache to redis.
  118. func (rc StandaloneRedisClient) LPush(key string, val interface{}) error {
  119. data, _ := json.Marshal(val)
  120. err := rc.redisClient.LPush(context.TODO(), key, data).Err()
  121. return err
  122. }
  123. func (rc StandaloneRedisClient) Brpop(key string, callback func([]byte)) {
  124. values, err := rc.redisClient.BRPop(context.TODO(), 1*time.Second, key).Result()
  125. if err != nil {
  126. return
  127. }
  128. if len(values) < 2 {
  129. fmt.Println("assert is wrong")
  130. return
  131. }
  132. callback([]byte(values[1]))
  133. }
  134. func (rc StandaloneRedisClient) GetRedisTTL(key string) time.Duration {
  135. value, err := rc.redisClient.TTL(context.TODO(), key).Result()
  136. if err != nil {
  137. return 0
  138. }
  139. return value
  140. }
  141. // Decr decrease counter in redis.
  142. func (rc StandaloneRedisClient) Incrby(key string, num int) (interface{}, error) {
  143. return rc.redisClient.IncrBy(context.TODO(), key, int64(num)).Result()
  144. }
  145. // actually do the redis cmds
  146. func (rc StandaloneRedisClient) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
  147. newArgs := make([]interface{}, 0)
  148. newArgs = append(newArgs, commandName, args)
  149. return rc.redisClient.Do(context.TODO(), commandName, newArgs).Result()
  150. }