redis.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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 int32 `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. //SetConn 设置conn
  43. func (r *Redis) SetConn(conn *redis.Pool) {
  44. r.conn = conn
  45. }
  46. //Get 获取一个值
  47. func (r *Redis) Get(key string) interface{} {
  48. conn := r.conn.Get()
  49. defer conn.Close()
  50. var data []byte
  51. var err error
  52. if data, err = redis.Bytes(conn.Do("GET", key)); err != nil {
  53. return nil
  54. }
  55. var reply interface{}
  56. if err = json.Unmarshal(data, &reply); err != nil {
  57. return nil
  58. }
  59. return reply
  60. }
  61. //Set 设置一个值
  62. func (r *Redis) Set(key string, val interface{}, timeout time.Duration) (err error) {
  63. conn := r.conn.Get()
  64. defer conn.Close()
  65. var data []byte
  66. if data, err = json.Marshal(val); err != nil {
  67. return
  68. }
  69. _, err = conn.Do("SETEX", key, int64(timeout/time.Second), data)
  70. return
  71. }
  72. //IsExist 判断key是否存在
  73. func (r *Redis) IsExist(key string) bool {
  74. conn := r.conn.Get()
  75. defer conn.Close()
  76. a, _ := conn.Do("EXISTS", key)
  77. i := a.(int64)
  78. if i > 0 {
  79. return true
  80. }
  81. return false
  82. }
  83. //Delete 删除
  84. func (r *Redis) Delete(key string) error {
  85. conn := r.conn.Get()
  86. defer conn.Close()
  87. if _, err := conn.Do("DEL", key); err != nil {
  88. return err
  89. }
  90. return nil
  91. }