蛋蛋星球-制度模式
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

redis.go 10 KiB

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