redis.go 2.1 KB

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