redis.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package cache
  2. import (
  3. "context"
  4. "time"
  5. "github.com/go-redis/redis/v8"
  6. )
  7. // Redis .redis cache
  8. // Deprecated: user defined implementation cache、ContextCache interface
  9. // The implementation was officially removed in v2.1.6
  10. type Redis struct {
  11. ctx context.Context
  12. conn redis.UniversalClient
  13. }
  14. // RedisOpts redis 连接属性
  15. type RedisOpts struct {
  16. Host string `yml:"host" json:"host"`
  17. Password string `yml:"password" json:"password"`
  18. Database int `yml:"database" json:"database"`
  19. MaxIdle int `yml:"max_idle" json:"max_idle"`
  20. MaxActive int `yml:"max_active" json:"max_active"`
  21. IdleTimeout int `yml:"idle_timeout" json:"idle_timeout"` // second
  22. }
  23. // NewRedis 实例化
  24. func NewRedis(ctx context.Context, opts *RedisOpts) *Redis {
  25. conn := redis.NewUniversalClient(&redis.UniversalOptions{
  26. Addrs: []string{opts.Host},
  27. DB: opts.Database,
  28. Password: opts.Password,
  29. IdleTimeout: time.Second * time.Duration(opts.IdleTimeout),
  30. MinIdleConns: opts.MaxIdle,
  31. })
  32. return &Redis{ctx: ctx, conn: conn}
  33. }
  34. // SetConn 设置 conn
  35. func (r *Redis) SetConn(conn redis.UniversalClient) {
  36. r.conn = conn
  37. }
  38. // SetRedisCtx 设置 redis ctx 参数
  39. func (r *Redis) SetRedisCtx(ctx context.Context) {
  40. r.ctx = ctx
  41. }
  42. // Get 获取一个值
  43. func (r *Redis) Get(key string) interface{} {
  44. return r.GetContext(r.ctx, key)
  45. }
  46. // GetContext 获取一个值
  47. func (r *Redis) GetContext(ctx context.Context, key string) interface{} {
  48. result, err := r.conn.Do(ctx, "GET", key).Result()
  49. if err != nil {
  50. return nil
  51. }
  52. return result
  53. }
  54. // Set 设置一个值
  55. func (r *Redis) Set(key string, val interface{}, timeout time.Duration) error {
  56. return r.SetContext(r.ctx, key, val, timeout)
  57. }
  58. // SetContext 设置一个值
  59. func (r *Redis) SetContext(ctx context.Context, key string, val interface{}, timeout time.Duration) error {
  60. return r.conn.SetEX(ctx, key, val, timeout).Err()
  61. }
  62. // IsExist 判断 key 是否存在
  63. func (r *Redis) IsExist(key string) bool {
  64. return r.IsExistContext(r.ctx, key)
  65. }
  66. // IsExistContext 判断 key 是否存在
  67. func (r *Redis) IsExistContext(ctx context.Context, key string) bool {
  68. result, _ := r.conn.Exists(ctx, key).Result()
  69. return result > 0
  70. }
  71. // Delete 删除
  72. func (r *Redis) Delete(key string) error {
  73. return r.DeleteContext(r.ctx, key)
  74. }
  75. // DeleteContext 删除
  76. func (r *Redis) DeleteContext(ctx context.Context, key string) error {
  77. return r.conn.Del(ctx, key).Err()
  78. }