redis.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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) *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. return redis.Dial("tcp", opts.Host,
  28. redis.DialDatabase(opts.Database),
  29. redis.DialPassword(opts.Password),
  30. )
  31. },
  32. TestOnBorrow: func(conn redis.Conn, t time.Time) error {
  33. if time.Since(t) < time.Minute {
  34. return nil
  35. }
  36. _, err := conn.Do("PING")
  37. return err
  38. },
  39. }
  40. return &Redis{pool}
  41. }
  42. //SetRedisPool 设置redis连接池
  43. func (r *Redis) SetRedisPool(pool *redis.Pool) {
  44. r.conn = pool
  45. }
  46. //SetConn 设置conn
  47. func (r *Redis) SetConn(conn *redis.Pool) {
  48. r.conn = conn
  49. }
  50. //Get 获取一个值
  51. func (r *Redis) Get(key string) interface{} {
  52. conn := r.conn.Get()
  53. defer conn.Close()
  54. var data []byte
  55. var err error
  56. if data, err = redis.Bytes(conn.Do("GET", key)); err != nil {
  57. return nil
  58. }
  59. var reply interface{}
  60. if err = json.Unmarshal(data, &reply); err != nil {
  61. return nil
  62. }
  63. return reply
  64. }
  65. //Set 设置一个值
  66. func (r *Redis) Set(key string, val interface{}, timeout time.Duration) (err error) {
  67. conn := r.conn.Get()
  68. defer conn.Close()
  69. var data []byte
  70. if data, err = json.Marshal(val); err != nil {
  71. return
  72. }
  73. _, err = conn.Do("SETEX", key, int64(timeout/time.Second), data)
  74. return
  75. }
  76. //IsExist 判断key是否存在
  77. func (r *Redis) IsExist(key string) bool {
  78. conn := r.conn.Get()
  79. defer conn.Close()
  80. a, _ := conn.Do("EXISTS", key)
  81. i := a.(int64)
  82. if i > 0 {
  83. return true
  84. }
  85. return false
  86. }
  87. //Delete 删除
  88. func (r *Redis) Delete(key string) error {
  89. conn := r.conn.Get()
  90. defer conn.Close()
  91. if _, err := conn.Do("DEL", key); err != nil {
  92. return err
  93. }
  94. return nil
  95. }