智慧食堂
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.

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