conf.go 1.7 KB

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