redis.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package cache
  2. import (
  3. "encoding/json"
  4. "time"
  5. "github.com/gomodule/redigo/redis"
  6. )
  7. // Redis .redis cache
  8. type Redis struct {
  9. conn *redis.Pool
  10. }
  11. // RedisOpts redis 连接属性
  12. type RedisOpts struct {
  13. Host string `yml:"host" json:"host"`
  14. Password string `yml:"password" json:"password"`
  15. Database int `yml:"database" json:"database"`
  16. MaxIdle int `yml:"max_idle" json:"max_idle"`
  17. MaxActive int `yml:"max_active" json:"max_active"`
  18. IdleTimeout int `yml:"idle_timeout" json:"idle_timeout"` // second
  19. }
  20. // NewRedis 实例化
  21. func NewRedis(opts *RedisOpts, dialOpts ...redis.DialOption) *Redis {
  22. pool := &redis.Pool{
  23. MaxActive: opts.MaxActive,
  24. MaxIdle: opts.MaxIdle,
  25. IdleTimeout: time.Second * time.Duration(opts.IdleTimeout),
  26. Dial: func() (redis.Conn, error) {
  27. dialOpts = append(dialOpts, []redis.DialOption{
  28. redis.DialDatabase(opts.Database),
  29. redis.DialPassword(opts.Password),
  30. }...)
  31. return redis.Dial("tcp", opts.Host, dialOpts...)
  32. },
  33. TestOnBorrow: func(conn redis.Conn, t time.Time) error {
  34. if time.Since(t) < time.Minute {
  35. return nil
  36. }
  37. _, err := conn.Do("PING")
  38. return err
  39. },
  40. }
  41. return &Redis{pool}
  42. }
  43. // SetRedisPool 设置redis连接池
  44. func (r *Redis) SetRedisPool(pool *redis.Pool) {
  45. r.conn = pool
  46. }
  47. // SetConn 设置conn
  48. func (r *Redis) SetConn(conn *redis.Pool) {
  49. r.conn = conn
  50. }
  51. // Get 获取一个值
  52. func (r *Redis) Get(key string) interface{} {
  53. conn := r.conn.Get()
  54. defer conn.Close()
  55. var data []byte
  56. var err error
  57. if data, err = redis.Bytes(conn.Do("GET", key)); err != nil {
  58. return nil
  59. }
  60. var reply interface{}
  61. if err = json.Unmarshal(data, &reply); err != nil {
  62. return nil
  63. }
  64. return reply
  65. }
  66. // Set 设置一个值
  67. func (r *Redis) Set(key string, val interface{}, timeout time.Duration) (err error) {
  68. conn := r.conn.Get()
  69. defer conn.Close()
  70. var data []byte
  71. if data, err = json.Marshal(val); err != nil {
  72. return
  73. }
  74. _, err = conn.Do("SETEX", key, int64(timeout/time.Second), data)
  75. return
  76. }
  77. // IsExist 判断key是否存在
  78. func (r *Redis) IsExist(key string) bool {
  79. conn := r.conn.Get()
  80. defer conn.Close()
  81. a, _ := conn.Do("EXISTS", key)
  82. i := a.(int64)
  83. return i > 0
  84. }
  85. // Delete 删除
  86. func (r *Redis) Delete(key string) error {
  87. conn := r.conn.Get()
  88. defer conn.Close()
  89. if _, err := conn.Do("DEL", key); err != nil {
  90. return err
  91. }
  92. return nil
  93. }