蛋蛋星球-客户端
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

redis.go 11 KiB

hace 1 mes
hace 3 semanas
hace 1 mes
hace 3 semanas
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. package cache
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "log"
  6. "strings"
  7. "time"
  8. redigo "github.com/gomodule/redigo/redis"
  9. )
  10. // configuration
  11. type Config struct {
  12. Server string
  13. Password string
  14. MaxIdle int // Maximum number of idle connections in the pool.
  15. // Maximum number of connections allocated by the pool at a given time.
  16. // When zero, there is no limit on the number of connections in the pool.
  17. MaxActive int
  18. // Close connections after remaining idle for this duration. If the value
  19. // is zero, then idle connections are not closed. Applications should set
  20. // the timeout to a value less than the server's timeout.
  21. IdleTimeout time.Duration
  22. // If Wait is true and the pool is at the MaxActive limit, then Get() waits
  23. // for a connection to be returned to the pool before returning.
  24. Wait bool
  25. KeyPrefix string // prefix to all keys; example is "dev environment name"
  26. KeyDelimiter string // delimiter to be used while appending keys; example is ":"
  27. KeyPlaceholder string // placeholder to be parsed using given arguments to obtain a final key; example is "?"
  28. }
  29. var pool *redigo.Pool
  30. var conf *Config
  31. func NewRedis(addr string) {
  32. if addr == "" {
  33. panic("\nredis connect string cannot be empty\n")
  34. }
  35. pool = &redigo.Pool{
  36. MaxIdle: redisMaxIdleConn,
  37. IdleTimeout: redisIdleTTL,
  38. MaxActive: redisMaxActive,
  39. // MaxConnLifetime: redisDialTTL,
  40. Wait: true,
  41. Dial: func() (redigo.Conn, error) {
  42. c, err := redigo.Dial("tcp", addr,
  43. redigo.DialConnectTimeout(redisDialTTL),
  44. redigo.DialReadTimeout(redisReadTTL),
  45. redigo.DialWriteTimeout(redisWriteTTL),
  46. )
  47. if err != nil {
  48. log.Println("Redis Dial failed: ", err)
  49. return nil, err
  50. }
  51. return c, err
  52. },
  53. TestOnBorrow: func(c redigo.Conn, t time.Time) error {
  54. _, err := c.Do("PING")
  55. if err != nil {
  56. log.Println("Unable to ping to redis server:", err)
  57. }
  58. return err
  59. },
  60. }
  61. conn := pool.Get()
  62. defer conn.Close()
  63. if conn.Err() != nil {
  64. println("\nredis connect " + addr + " error: " + conn.Err().Error())
  65. } else {
  66. println("\nredis connect " + addr + " success!\n")
  67. }
  68. }
  69. func Do(cmd string, args ...interface{}) (reply interface{}, err error) {
  70. conn := pool.Get()
  71. defer conn.Close()
  72. return conn.Do(cmd, args...)
  73. }
  74. func GetPool() *redigo.Pool {
  75. return pool
  76. }
  77. func ParseKey(key string, vars []string) (string, error) {
  78. arr := strings.Split(key, conf.KeyPlaceholder)
  79. actualKey := ""
  80. if len(arr) != len(vars)+1 {
  81. return "", errors.New("redis/connection.go: Insufficient arguments to parse key")
  82. } else {
  83. for index, val := range arr {
  84. if index == 0 {
  85. actualKey = arr[index]
  86. } else {
  87. actualKey += vars[index-1] + val
  88. }
  89. }
  90. }
  91. return getPrefixedKey(actualKey), nil
  92. }
  93. func getPrefixedKey(key string) string {
  94. return conf.KeyPrefix + conf.KeyDelimiter + key
  95. }
  96. func StripEnvKey(key string) string {
  97. return strings.TrimLeft(key, conf.KeyPrefix+conf.KeyDelimiter)
  98. }
  99. func SplitKey(key string) []string {
  100. return strings.Split(key, conf.KeyDelimiter)
  101. }
  102. func Expire(key string, ttl int) (interface{}, error) {
  103. return Do("EXPIRE", key, ttl)
  104. }
  105. func Persist(key string) (interface{}, error) {
  106. return Do("PERSIST", key)
  107. }
  108. func Del(key string) (interface{}, error) {
  109. return Do("DEL", key)
  110. }
  111. func Set(key string, data interface{}) (interface{}, error) {
  112. // set
  113. return Do("SET", key, data)
  114. }
  115. func SetNX(key string, data interface{}) (interface{}, error) {
  116. return Do("SETNX", key, data)
  117. }
  118. func SetEx(key string, data interface{}, ttl int) (interface{}, error) {
  119. return Do("SETEX", key, ttl, data)
  120. }
  121. func SetJson(key string, data interface{}, ttl int) bool {
  122. c, err := json.Marshal(data)
  123. if err != nil {
  124. return false
  125. }
  126. if ttl < 1 {
  127. _, err = Set(key, c)
  128. } else {
  129. _, err = SetEx(key, c, ttl)
  130. }
  131. if err != nil {
  132. return false
  133. }
  134. return true
  135. }
  136. func GetJson(key string, dst interface{}) error {
  137. b, err := GetBytes(key)
  138. if err != nil {
  139. return err
  140. }
  141. if err = json.Unmarshal(b, dst); err != nil {
  142. return err
  143. }
  144. return nil
  145. }
  146. func Get(key string) (interface{}, error) {
  147. // get
  148. return Do("GET", key)
  149. }
  150. func GetBit(key string, offset int64) (int64, error) {
  151. return redigo.Int64(Do("GETBIT", key, offset))
  152. }
  153. func SetBit(key string, offset int64, value int) (interface{}, error) {
  154. return Do("SETBIT", key, offset, value)
  155. }
  156. func GetTTL(key string) (time.Duration, error) {
  157. ttl, err := redigo.Int64(Do("TTL", key))
  158. return time.Duration(ttl) * time.Second, err
  159. }
  160. func GetBytes(key string) ([]byte, error) {
  161. return redigo.Bytes(Do("GET", key))
  162. }
  163. func GetString(key string) (string, error) {
  164. return redigo.String(Do("GET", key))
  165. }
  166. func GetStringMap(key string) (map[string]string, error) {
  167. return redigo.StringMap(Do("GET", key))
  168. }
  169. func GetInt(key string) (int, error) {
  170. return redigo.Int(Do("GET", key))
  171. }
  172. func GetInt64(key string) (int64, error) {
  173. return redigo.Int64(Do("GET", key))
  174. }
  175. func GetStringLength(key string) (int, error) {
  176. return redigo.Int(Do("STRLEN", key))
  177. }
  178. func ZAdd(key string, score float64, data interface{}) (interface{}, error) {
  179. return Do("ZADD", key, score, data)
  180. }
  181. func ZAddNX(key string, score float64, data interface{}) (interface{}, error) {
  182. return Do("ZADD", key, "NX", score, data)
  183. }
  184. func ZRem(key string, data interface{}) (interface{}, error) {
  185. return Do("ZREM", key, data)
  186. }
  187. func ZRange(key string, start int, end int, withScores bool) ([]interface{}, error) {
  188. if withScores {
  189. return redigo.Values(Do("ZRANGE", key, start, end, "WITHSCORES"))
  190. }
  191. return redigo.Values(Do("ZRANGE", key, start, end))
  192. }
  193. func ZRemRangeByScore(key string, start int64, end int64) ([]interface{}, error) {
  194. return redigo.Values(Do("ZREMRANGEBYSCORE", key, start, end))
  195. }
  196. func ZCard(setName string) (int64, error) {
  197. return redigo.Int64(Do("ZCARD", setName))
  198. }
  199. func ZScan(setName string) (int64, error) {
  200. return redigo.Int64(Do("ZCARD", setName))
  201. }
  202. func SAdd(setName string, data interface{}) (interface{}, error) {
  203. return Do("SADD", setName, data)
  204. }
  205. func SCard(setName string) (int64, error) {
  206. return redigo.Int64(Do("SCARD", setName))
  207. }
  208. func SIsMember(setName string, data interface{}) (bool, error) {
  209. return redigo.Bool(Do("SISMEMBER", setName, data))
  210. }
  211. func SMembers(setName string) ([]string, error) {
  212. return redigo.Strings(Do("SMEMBERS", setName))
  213. }
  214. func SRem(setName string, data interface{}) (interface{}, error) {
  215. return Do("SREM", setName, data)
  216. }
  217. func HSet(key string, HKey string, data interface{}) (interface{}, error) {
  218. return Do("HSET", key, HKey, data)
  219. }
  220. func HGet(key string, HKey string) (interface{}, error) {
  221. return Do("HGET", key, HKey)
  222. }
  223. func HMGet(key string, hashKeys ...string) ([]interface{}, error) {
  224. ret, err := Do("HMGET", key, hashKeys)
  225. if err != nil {
  226. return nil, err
  227. }
  228. reta, ok := ret.([]interface{})
  229. if !ok {
  230. return nil, errors.New("result not an array")
  231. }
  232. return reta, nil
  233. }
  234. func HMSet(key string, hashKeys []string, vals []interface{}) (interface{}, error) {
  235. if len(hashKeys) == 0 || len(hashKeys) != len(vals) {
  236. var ret interface{}
  237. return ret, errors.New("bad length")
  238. }
  239. input := []interface{}{key}
  240. for i, v := range hashKeys {
  241. input = append(input, v, vals[i])
  242. }
  243. return Do("HMSET", input...)
  244. }
  245. func HGetString(key string, HKey string) (string, error) {
  246. return redigo.String(Do("HGET", key, HKey))
  247. }
  248. func HGetFloat(key string, HKey string) (float64, error) {
  249. f, err := redigo.Float64(Do("HGET", key, HKey))
  250. return f, err
  251. }
  252. func HGetInt(key string, HKey string) (int, error) {
  253. return redigo.Int(Do("HGET", key, HKey))
  254. }
  255. func HGetInt64(key string, HKey string) (int64, error) {
  256. return redigo.Int64(Do("HGET", key, HKey))
  257. }
  258. func HGetBool(key string, HKey string) (bool, error) {
  259. return redigo.Bool(Do("HGET", key, HKey))
  260. }
  261. func HDel(key string, HKey string) (interface{}, error) {
  262. return Do("HDEL", key, HKey)
  263. }
  264. func HGetAll(key string) (map[string]interface{}, error) {
  265. vals, err := redigo.Values(Do("HGETALL", key))
  266. if err != nil {
  267. return nil, err
  268. }
  269. num := len(vals) / 2
  270. result := make(map[string]interface{}, num)
  271. for i := 0; i < num; i++ {
  272. key, _ := redigo.String(vals[2*i], nil)
  273. result[key] = vals[2*i+1]
  274. }
  275. return result, nil
  276. }
  277. func FlushAll() bool {
  278. res, _ := redigo.String(Do("FLUSHALL"))
  279. if res == "" {
  280. return false
  281. }
  282. return true
  283. }
  284. // NOTE: Use this in production environment with extreme care.
  285. // Read more here:https://redigo.io/commands/keys
  286. func Keys(pattern string) ([]string, error) {
  287. return redigo.Strings(Do("KEYS", pattern))
  288. }
  289. func HKeys(key string) ([]string, error) {
  290. return redigo.Strings(Do("HKEYS", key))
  291. }
  292. func Exists(key string) bool {
  293. count, err := redigo.Int(Do("EXISTS", key))
  294. if count == 0 || err != nil {
  295. return false
  296. }
  297. return true
  298. }
  299. func Incr(key string) (int64, error) {
  300. return redigo.Int64(Do("INCR", key))
  301. }
  302. func Decr(key string) (int64, error) {
  303. return redigo.Int64(Do("DECR", key))
  304. }
  305. func IncrBy(key string, incBy int64) (int64, error) {
  306. return redigo.Int64(Do("INCRBY", key, incBy))
  307. }
  308. func DecrBy(key string, decrBy int64) (int64, error) {
  309. return redigo.Int64(Do("DECRBY", key))
  310. }
  311. func IncrByFloat(key string, incBy float64) (float64, error) {
  312. return redigo.Float64(Do("INCRBYFLOAT", key, incBy))
  313. }
  314. func DecrByFloat(key string, decrBy float64) (float64, error) {
  315. return redigo.Float64(Do("DECRBYFLOAT", key, decrBy))
  316. }
  317. // use for message queue
  318. func LPush(key string, data interface{}) (interface{}, error) {
  319. // set
  320. return Do("LPUSH", key, data)
  321. }
  322. func LPop(key string) (interface{}, error) {
  323. return Do("LPOP", key)
  324. }
  325. func LPopString(key string) (string, error) {
  326. return redigo.String(Do("LPOP", key))
  327. }
  328. func LPopFloat(key string) (float64, error) {
  329. f, err := redigo.Float64(Do("LPOP", key))
  330. return f, err
  331. }
  332. func LPopInt(key string) (int, error) {
  333. return redigo.Int(Do("LPOP", key))
  334. }
  335. func LPopInt64(key string) (int64, error) {
  336. return redigo.Int64(Do("LPOP", key))
  337. }
  338. func RPush(key string, data interface{}) (interface{}, error) {
  339. // set
  340. return Do("RPUSH", key, data)
  341. }
  342. func RPop(key string) (interface{}, error) {
  343. return Do("RPOP", key)
  344. }
  345. func RPopString(key string) (string, error) {
  346. return redigo.String(Do("RPOP", key))
  347. }
  348. func RPopFloat(key string) (float64, error) {
  349. f, err := redigo.Float64(Do("RPOP", key))
  350. return f, err
  351. }
  352. func RPopInt(key string) (int, error) {
  353. return redigo.Int(Do("RPOP", key))
  354. }
  355. func RPopInt64(key string) (int64, error) {
  356. return redigo.Int64(Do("RPOP", key))
  357. }
  358. func Scan(cursor int64, pattern string, count int64) (int64, []string, error) {
  359. var items []string
  360. var newCursor int64
  361. values, err := redigo.Values(Do("SCAN", cursor, "MATCH", pattern, "COUNT", count))
  362. if err != nil {
  363. return 0, nil, err
  364. }
  365. values, err = redigo.Scan(values, &newCursor, &items)
  366. if err != nil {
  367. return 0, nil, err
  368. }
  369. return newCursor, items, nil
  370. }
  371. func LPushMax(key string, data ...interface{}) (interface{}, error) {
  372. // set
  373. return Do("LPUSH", key, data)
  374. }