redis.go 2.3 KB

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