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. 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. Username string `yaml:"username" json:"username"`
  16. Password string `yml:"password" json:"password"`
  17. Database int `yml:"database" json:"database"`
  18. MaxIdle int `yml:"max_idle" json:"max_idle"`
  19. MaxActive int `yml:"max_active" json:"max_active"`
  20. IdleTimeout int `yml:"idle_timeout" json:"idle_timeout"` // second
  21. }
  22. // NewRedis 实例化
  23. func NewRedis(ctx context.Context, opts *RedisOpts) *Redis {
  24. conn := redis.NewUniversalClient(&redis.UniversalOptions{
  25. Addrs: []string{opts.Host},
  26. DB: opts.Database,
  27. Username: opts.Username,
  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. }