蛋蛋星球 后台端
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

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