蛋蛋星球 后台端
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1 个月前
3 周前
1 个月前
3 周前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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 SelectDb(db int) (interface{}, error) {
  122. return Do("SELECT", db)
  123. }
  124. func SetJson(key string, data interface{}, ttl int) bool {
  125. c, err := json.Marshal(data)
  126. if err != nil {
  127. return false
  128. }
  129. if ttl < 1 {
  130. _, err = Set(key, c)
  131. } else {
  132. _, err = SetEx(key, c, ttl)
  133. }
  134. if err != nil {
  135. return false
  136. }
  137. return true
  138. }
  139. func GetJson(key string, dst interface{}) error {
  140. b, err := GetBytes(key)
  141. if err != nil {
  142. return err
  143. }
  144. if err = json.Unmarshal(b, dst); err != nil {
  145. return err
  146. }
  147. return nil
  148. }
  149. func Get(key string) (interface{}, error) {
  150. // get
  151. return Do("GET", key)
  152. }
  153. func GetTTL(key string) (time.Duration, error) {
  154. ttl, err := redigo.Int64(Do("TTL", key))
  155. return time.Duration(ttl) * time.Second, err
  156. }
  157. func GetBytes(key string) ([]byte, error) {
  158. return redigo.Bytes(Do("GET", key))
  159. }
  160. func GetString(key string) (string, error) {
  161. return redigo.String(Do("GET", key))
  162. }
  163. func GetStringMap(key string) (map[string]string, error) {
  164. return redigo.StringMap(Do("GET", key))
  165. }
  166. func GetInt(key string) (int, error) {
  167. return redigo.Int(Do("GET", key))
  168. }
  169. func GetInt64(key string) (int64, error) {
  170. return redigo.Int64(Do("GET", key))
  171. }
  172. func GetStringLength(key string) (int, error) {
  173. return redigo.Int(Do("STRLEN", key))
  174. }
  175. func ZAdd(key string, score float64, data interface{}) (interface{}, error) {
  176. return Do("ZADD", key, score, data)
  177. }
  178. func ZAddNX(key string, score float64, data interface{}) (interface{}, error) {
  179. return Do("ZADD", key, "NX", score, data)
  180. }
  181. func ZRem(key string, data interface{}) (interface{}, error) {
  182. return Do("ZREM", key, data)
  183. }
  184. func ZRange(key string, start int, end int, withScores bool) ([]interface{}, error) {
  185. if withScores {
  186. return redigo.Values(Do("ZRANGE", key, start, end, "WITHSCORES"))
  187. }
  188. return redigo.Values(Do("ZRANGE", key, start, end))
  189. }
  190. func ZRemRangeByScore(key string, start int64, end int64) ([]interface{}, error) {
  191. return redigo.Values(Do("ZREMRANGEBYSCORE", key, start, end))
  192. }
  193. func ZCard(setName string) (int64, error) {
  194. return redigo.Int64(Do("ZCARD", setName))
  195. }
  196. func ZScan(setName string) (int64, error) {
  197. return redigo.Int64(Do("ZCARD", setName))
  198. }
  199. func SAdd(setName string, data interface{}) (interface{}, error) {
  200. return Do("SADD", setName, data)
  201. }
  202. func SCard(setName string) (int64, error) {
  203. return redigo.Int64(Do("SCARD", setName))
  204. }
  205. func SIsMember(setName string, data interface{}) (bool, error) {
  206. return redigo.Bool(Do("SISMEMBER", setName, data))
  207. }
  208. func SMembers(setName string) ([]string, error) {
  209. return redigo.Strings(Do("SMEMBERS", setName))
  210. }
  211. func SRem(setName string, data interface{}) (interface{}, error) {
  212. return Do("SREM", setName, data)
  213. }
  214. func HSet(key string, HKey string, data interface{}) (interface{}, error) {
  215. return Do("HSET", key, HKey, data)
  216. }
  217. func HGet(key string, HKey string) (interface{}, error) {
  218. return Do("HGET", key, HKey)
  219. }
  220. func HMGet(key string, hashKeys ...string) ([]interface{}, error) {
  221. ret, err := Do("HMGET", key, hashKeys)
  222. if err != nil {
  223. return nil, err
  224. }
  225. reta, ok := ret.([]interface{})
  226. if !ok {
  227. return nil, errors.New("result not an array")
  228. }
  229. return reta, nil
  230. }
  231. func HMSet(key string, hashKeys []string, vals []interface{}) (interface{}, error) {
  232. if len(hashKeys) == 0 || len(hashKeys) != len(vals) {
  233. var ret interface{}
  234. return ret, errors.New("bad length")
  235. }
  236. input := []interface{}{key}
  237. for i, v := range hashKeys {
  238. input = append(input, v, vals[i])
  239. }
  240. return Do("HMSET", input...)
  241. }
  242. func HGetString(key string, HKey string) (string, error) {
  243. return redigo.String(Do("HGET", key, HKey))
  244. }
  245. func HGetFloat(key string, HKey string) (float64, error) {
  246. f, err := redigo.Float64(Do("HGET", key, HKey))
  247. return f, err
  248. }
  249. func HGetInt(key string, HKey string) (int, error) {
  250. return redigo.Int(Do("HGET", key, HKey))
  251. }
  252. func HGetInt64(key string, HKey string) (int64, error) {
  253. return redigo.Int64(Do("HGET", key, HKey))
  254. }
  255. func HGetBool(key string, HKey string) (bool, error) {
  256. return redigo.Bool(Do("HGET", key, HKey))
  257. }
  258. func HDel(key string, HKey string) (interface{}, error) {
  259. return Do("HDEL", key, HKey)
  260. }
  261. func HGetAll(key string) (map[string]interface{}, error) {
  262. vals, err := redigo.Values(Do("HGETALL", key))
  263. if err != nil {
  264. return nil, err
  265. }
  266. num := len(vals) / 2
  267. result := make(map[string]interface{}, num)
  268. for i := 0; i < num; i++ {
  269. key, _ := redigo.String(vals[2*i], nil)
  270. result[key] = vals[2*i+1]
  271. }
  272. return result, nil
  273. }
  274. func FlushAll() bool {
  275. res, _ := redigo.String(Do("FLUSHALL"))
  276. if res == "" {
  277. return false
  278. }
  279. return true
  280. }
  281. // NOTE: Use this in production environment with extreme care.
  282. // Read more here:https://redigo.io/commands/keys
  283. func Keys(pattern string) ([]string, error) {
  284. return redigo.Strings(Do("KEYS", pattern))
  285. }
  286. func HKeys(key string) ([]string, error) {
  287. return redigo.Strings(Do("HKEYS", key))
  288. }
  289. func Exists(key string) bool {
  290. count, err := redigo.Int(Do("EXISTS", key))
  291. if count == 0 || err != nil {
  292. return false
  293. }
  294. return true
  295. }
  296. func Incr(key string) (int64, error) {
  297. return redigo.Int64(Do("INCR", key))
  298. }
  299. func Decr(key string) (int64, error) {
  300. return redigo.Int64(Do("DECR", key))
  301. }
  302. func IncrBy(key string, incBy int64) (int64, error) {
  303. return redigo.Int64(Do("INCRBY", key, incBy))
  304. }
  305. func DecrBy(key string, decrBy int64) (int64, error) {
  306. return redigo.Int64(Do("DECRBY", key))
  307. }
  308. func IncrByFloat(key string, incBy float64) (float64, error) {
  309. return redigo.Float64(Do("INCRBYFLOAT", key, incBy))
  310. }
  311. func DecrByFloat(key string, decrBy float64) (float64, error) {
  312. return redigo.Float64(Do("DECRBYFLOAT", key, decrBy))
  313. }
  314. // use for message queue
  315. func LPush(key string, data interface{}) (interface{}, error) {
  316. // set
  317. return Do("LPUSH", key, data)
  318. }
  319. func LPop(key string) (interface{}, error) {
  320. return Do("LPOP", key)
  321. }
  322. func LPopString(key string) (string, error) {
  323. return redigo.String(Do("LPOP", key))
  324. }
  325. func LPopFloat(key string) (float64, error) {
  326. f, err := redigo.Float64(Do("LPOP", key))
  327. return f, err
  328. }
  329. func LPopInt(key string) (int, error) {
  330. return redigo.Int(Do("LPOP", key))
  331. }
  332. func LPopInt64(key string) (int64, error) {
  333. return redigo.Int64(Do("LPOP", key))
  334. }
  335. func RPush(key string, data interface{}) (interface{}, error) {
  336. // set
  337. return Do("RPUSH", key, data)
  338. }
  339. func RPop(key string) (interface{}, error) {
  340. return Do("RPOP", key)
  341. }
  342. func RPopString(key string) (string, error) {
  343. return redigo.String(Do("RPOP", key))
  344. }
  345. func RPopFloat(key string) (float64, error) {
  346. f, err := redigo.Float64(Do("RPOP", key))
  347. return f, err
  348. }
  349. func RPopInt(key string) (int, error) {
  350. return redigo.Int(Do("RPOP", key))
  351. }
  352. func RPopInt64(key string) (int64, error) {
  353. return redigo.Int64(Do("RPOP", key))
  354. }
  355. func Scan(cursor int64, pattern string, count int64) (int64, []string, error) {
  356. var items []string
  357. var newCursor int64
  358. values, err := redigo.Values(Do("SCAN", cursor, "MATCH", pattern, "COUNT", count))
  359. if err != nil {
  360. return 0, nil, err
  361. }
  362. values, err = redigo.Scan(values, &newCursor, &items)
  363. if err != nil {
  364. return 0, nil, err
  365. }
  366. return newCursor, items, nil
  367. }
  368. func LPushMax(key string, data ...interface{}) (interface{}, error) {
  369. // set
  370. return Do("LPUSH", key, data)
  371. }