附近小店
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.
 
 
 

407 regels
10 KiB

  1. package cachesecond
  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.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. if pwd != "" {
  52. c.Send("auth", pwd)
  53. }
  54. return c, err
  55. },
  56. TestOnBorrow: func(c redigo.Conn, t time.Time) error {
  57. _, err := c.Do("PING")
  58. if err != nil {
  59. log.Println("Unable to ping to redis server:", err)
  60. }
  61. return err
  62. },
  63. }
  64. conn := pool.Get()
  65. defer conn.Close()
  66. if conn.Err() != nil {
  67. println("\nredis connect " + addr + " error: " + conn.Err().Error())
  68. } else {
  69. println("\nredis connect " + addr + " success!\n")
  70. }
  71. }
  72. func Do(cmd string, args ...interface{}) (reply interface{}, err error) {
  73. conn := pool.Get()
  74. defer conn.Close()
  75. return conn.Do(cmd, args...)
  76. }
  77. func GetPool() *redigo.Pool {
  78. return pool
  79. }
  80. func ParseKey(key string, vars []string) (string, error) {
  81. arr := strings.Split(key, conf.KeyPlaceholder)
  82. actualKey := ""
  83. if len(arr) != len(vars)+1 {
  84. return "", errors.New("redis/connection.go: Insufficient arguments to parse key")
  85. } else {
  86. for index, val := range arr {
  87. if index == 0 {
  88. actualKey = arr[index]
  89. } else {
  90. actualKey += vars[index-1] + val
  91. }
  92. }
  93. }
  94. return getPrefixedKey(actualKey), nil
  95. }
  96. func getPrefixedKey(key string) string {
  97. return conf.KeyPrefix + conf.KeyDelimiter + key
  98. }
  99. func StripEnvKey(key string) string {
  100. return strings.TrimLeft(key, conf.KeyPrefix+conf.KeyDelimiter)
  101. }
  102. func SplitKey(key string) []string {
  103. return strings.Split(key, conf.KeyDelimiter)
  104. }
  105. func Expire(key string, ttl int) (interface{}, error) {
  106. return Do("EXPIRE", key, ttl)
  107. }
  108. func Persist(key string) (interface{}, error) {
  109. return Do("PERSIST", key)
  110. }
  111. func Del(key string) (interface{}, error) {
  112. return Do("DEL", key)
  113. }
  114. func Set(key string, data interface{}) (interface{}, error) {
  115. // set
  116. return Do("SET", key, data)
  117. }
  118. func SetNX(key string, data interface{}) (interface{}, error) {
  119. return Do("SETNX", key, data)
  120. }
  121. func SetEx(key string, data interface{}, ttl int) (interface{}, error) {
  122. return Do("SETEX", key, ttl, data)
  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. }