conf.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package redis
  2. import (
  3. "errors"
  4. "time"
  5. )
  6. var (
  7. // ErrEmptyHost is an error that indicates no redis host is set.
  8. ErrEmptyHost = errors.New("empty redis host")
  9. // ErrEmptyType is an error that indicates no redis type is set.
  10. ErrEmptyType = errors.New("empty redis type")
  11. // ErrEmptyKey is an error that indicates no redis key is set.
  12. ErrEmptyKey = errors.New("empty redis key")
  13. )
  14. type (
  15. // A RedisConf is a redis config.
  16. RedisConf struct {
  17. Host string
  18. Type string `json:",default=node,options=node|cluster"`
  19. Pass string `json:",optional"`
  20. Tls bool `json:",optional"`
  21. NonBlock bool `json:",default=true"`
  22. // PingTimeout is the timeout for ping redis.
  23. PingTimeout time.Duration `json:",default=1s"`
  24. }
  25. // A RedisKeyConf is a redis config with key.
  26. RedisKeyConf struct {
  27. RedisConf
  28. Key string
  29. }
  30. )
  31. // NewRedis returns a Redis.
  32. // Deprecated: use MustNewRedis or NewRedis instead.
  33. func (rc RedisConf) NewRedis() *Redis {
  34. var opts []Option
  35. if rc.Type == ClusterType {
  36. opts = append(opts, Cluster())
  37. }
  38. if len(rc.Pass) > 0 {
  39. opts = append(opts, WithPass(rc.Pass))
  40. }
  41. if rc.Tls {
  42. opts = append(opts, WithTLS())
  43. }
  44. return New(rc.Host, opts...)
  45. }
  46. // Validate validates the RedisConf.
  47. func (rc RedisConf) Validate() error {
  48. if len(rc.Host) == 0 {
  49. return ErrEmptyHost
  50. }
  51. if len(rc.Type) == 0 {
  52. return ErrEmptyType
  53. }
  54. return nil
  55. }
  56. // Validate validates the RedisKeyConf.
  57. func (rkc RedisKeyConf) Validate() error {
  58. if err := rkc.RedisConf.Validate(); err != nil {
  59. return err
  60. }
  61. if len(rkc.Key) == 0 {
  62. return ErrEmptyKey
  63. }
  64. return nil
  65. }