蛋蛋星球-客户端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

429 lines
11 KiB

  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 ZRevRange(key string, start int, end int, withScores bool) ([]interface{}, error) {
  194. if withScores {
  195. return redigo.Values(Do("ZREVRANGE", key, start, end, "WITHSCORES"))
  196. }
  197. return redigo.Values(Do("ZREVRANGE", key, start, end))
  198. }
  199. func ZRevRangeByMember(key string, member string) (int64, error) {
  200. return redigo.Int64(Do("ZREVRANK", key, member))
  201. }
  202. func ZScoreByMember(key string, member string) (float64, error) {
  203. return redigo.Float64(Do("ZSCORE", key, member))
  204. }
  205. func ZRemRangeByScore(key string, start int64, end int64) ([]interface{}, error) {
  206. return redigo.Values(Do("ZREMRANGEBYSCORE", key, start, end))
  207. }
  208. func ZCard(setName string) (int64, error) {
  209. return redigo.Int64(Do("ZCARD", setName))
  210. }
  211. func ZScan(setName string) (int64, error) {
  212. return redigo.Int64(Do("ZCARD", setName))
  213. }
  214. func SAdd(setName string, data interface{}) (interface{}, error) {
  215. return Do("SADD", setName, data)
  216. }
  217. func SCard(setName string) (int64, error) {
  218. return redigo.Int64(Do("SCARD", setName))
  219. }
  220. func SIsMember(setName string, data interface{}) (bool, error) {
  221. return redigo.Bool(Do("SISMEMBER", setName, data))
  222. }
  223. func SMembers(setName string) ([]string, error) {
  224. return redigo.Strings(Do("SMEMBERS", setName))
  225. }
  226. func SRem(setName string, data interface{}) (interface{}, error) {
  227. return Do("SREM", setName, data)
  228. }
  229. func HSet(key string, HKey string, data interface{}) (interface{}, error) {
  230. return Do("HSET", key, HKey, data)
  231. }
  232. func HGet(key string, HKey string) (interface{}, error) {
  233. return Do("HGET", key, HKey)
  234. }
  235. func HMGet(key string, hashKeys ...string) ([]interface{}, error) {
  236. ret, err := Do("HMGET", key, hashKeys)
  237. if err != nil {
  238. return nil, err
  239. }
  240. reta, ok := ret.([]interface{})
  241. if !ok {
  242. return nil, errors.New("result not an array")
  243. }
  244. return reta, nil
  245. }
  246. func HMSet(key string, hashKeys []string, vals []interface{}) (interface{}, error) {
  247. if len(hashKeys) == 0 || len(hashKeys) != len(vals) {
  248. var ret interface{}
  249. return ret, errors.New("bad length")
  250. }
  251. input := []interface{}{key}
  252. for i, v := range hashKeys {
  253. input = append(input, v, vals[i])
  254. }
  255. return Do("HMSET", input...)
  256. }
  257. func HGetString(key string, HKey string) (string, error) {
  258. return redigo.String(Do("HGET", key, HKey))
  259. }
  260. func HGetFloat(key string, HKey string) (float64, error) {
  261. f, err := redigo.Float64(Do("HGET", key, HKey))
  262. return f, err
  263. }
  264. func HGetInt(key string, HKey string) (int, error) {
  265. return redigo.Int(Do("HGET", key, HKey))
  266. }
  267. func HGetInt64(key string, HKey string) (int64, error) {
  268. return redigo.Int64(Do("HGET", key, HKey))
  269. }
  270. func HGetBool(key string, HKey string) (bool, error) {
  271. return redigo.Bool(Do("HGET", key, HKey))
  272. }
  273. func HDel(key string, HKey string) (interface{}, error) {
  274. return Do("HDEL", key, HKey)
  275. }
  276. func HGetAll(key string) (map[string]interface{}, error) {
  277. vals, err := redigo.Values(Do("HGETALL", key))
  278. if err != nil {
  279. return nil, err
  280. }
  281. num := len(vals) / 2
  282. result := make(map[string]interface{}, num)
  283. for i := 0; i < num; i++ {
  284. key, _ := redigo.String(vals[2*i], nil)
  285. result[key] = vals[2*i+1]
  286. }
  287. return result, nil
  288. }
  289. func FlushAll() bool {
  290. res, _ := redigo.String(Do("FLUSHALL"))
  291. if res == "" {
  292. return false
  293. }
  294. return true
  295. }
  296. // NOTE: Use this in production environment with extreme care.
  297. // Read more here:https://redigo.io/commands/keys
  298. func Keys(pattern string) ([]string, error) {
  299. return redigo.Strings(Do("KEYS", pattern))
  300. }
  301. func HKeys(key string) ([]string, error) {
  302. return redigo.Strings(Do("HKEYS", key))
  303. }
  304. func Exists(key string) bool {
  305. count, err := redigo.Int(Do("EXISTS", key))
  306. if count == 0 || err != nil {
  307. return false
  308. }
  309. return true
  310. }
  311. func Incr(key string) (int64, error) {
  312. return redigo.Int64(Do("INCR", key))
  313. }
  314. func Decr(key string) (int64, error) {
  315. return redigo.Int64(Do("DECR", key))
  316. }
  317. func IncrBy(key string, incBy int64) (int64, error) {
  318. return redigo.Int64(Do("INCRBY", key, incBy))
  319. }
  320. func DecrBy(key string, decrBy int64) (int64, error) {
  321. return redigo.Int64(Do("DECRBY", key))
  322. }
  323. func IncrByFloat(key string, incBy float64) (float64, error) {
  324. return redigo.Float64(Do("INCRBYFLOAT", key, incBy))
  325. }
  326. func DecrByFloat(key string, decrBy float64) (float64, error) {
  327. return redigo.Float64(Do("DECRBYFLOAT", key, decrBy))
  328. }
  329. // use for message queue
  330. func LPush(key string, data interface{}) (interface{}, error) {
  331. // set
  332. return Do("LPUSH", key, data)
  333. }
  334. func LPop(key string) (interface{}, error) {
  335. return Do("LPOP", key)
  336. }
  337. func LPopString(key string) (string, error) {
  338. return redigo.String(Do("LPOP", key))
  339. }
  340. func LPopFloat(key string) (float64, error) {
  341. f, err := redigo.Float64(Do("LPOP", key))
  342. return f, err
  343. }
  344. func LPopInt(key string) (int, error) {
  345. return redigo.Int(Do("LPOP", key))
  346. }
  347. func LPopInt64(key string) (int64, error) {
  348. return redigo.Int64(Do("LPOP", key))
  349. }
  350. func RPush(key string, data interface{}) (interface{}, error) {
  351. // set
  352. return Do("RPUSH", key, data)
  353. }
  354. func RPop(key string) (interface{}, error) {
  355. return Do("RPOP", key)
  356. }
  357. func RPopString(key string) (string, error) {
  358. return redigo.String(Do("RPOP", key))
  359. }
  360. func RPopFloat(key string) (float64, error) {
  361. f, err := redigo.Float64(Do("RPOP", key))
  362. return f, err
  363. }
  364. func RPopInt(key string) (int, error) {
  365. return redigo.Int(Do("RPOP", key))
  366. }
  367. func RPopInt64(key string) (int64, error) {
  368. return redigo.Int64(Do("RPOP", key))
  369. }
  370. func Scan(cursor int64, pattern string, count int64) (int64, []string, error) {
  371. var items []string
  372. var newCursor int64
  373. values, err := redigo.Values(Do("SCAN", cursor, "MATCH", pattern, "COUNT", count))
  374. if err != nil {
  375. return 0, nil, err
  376. }
  377. values, err = redigo.Scan(values, &newCursor, &items)
  378. if err != nil {
  379. return 0, nil, err
  380. }
  381. return newCursor, items, nil
  382. }
  383. func LPushMax(key string, data ...interface{}) (interface{}, error) {
  384. // set
  385. return Do("LPUSH", key, data)
  386. }