redisclientmanager.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package redis
  2. import (
  3. "crypto/tls"
  4. "io"
  5. "runtime"
  6. red "github.com/go-redis/redis/v8"
  7. "github.com/wuntsong-org/go-zero-plus/core/syncx"
  8. )
  9. const (
  10. defaultDatabase = 0
  11. maxRetries = 3
  12. idleConns = 8
  13. )
  14. var (
  15. clientManager = syncx.NewResourceManager()
  16. // nodePoolSize is default pool size for node type of redis.
  17. nodePoolSize = 10 * runtime.GOMAXPROCS(0)
  18. )
  19. func getClient(r *Redis) (*red.Client, error) {
  20. val, err := clientManager.GetResource(r.Addr, func() (io.Closer, error) {
  21. var tlsConfig *tls.Config
  22. if r.tls {
  23. tlsConfig = &tls.Config{
  24. InsecureSkipVerify: true,
  25. }
  26. }
  27. store := red.NewClient(&red.Options{
  28. Addr: r.Addr,
  29. Password: r.Pass,
  30. DB: defaultDatabase,
  31. MaxRetries: maxRetries,
  32. MinIdleConns: idleConns,
  33. TLSConfig: tlsConfig,
  34. })
  35. store.AddHook(durationHook)
  36. for _, hook := range r.hooks {
  37. store.AddHook(hook)
  38. }
  39. connCollector.registerClient(&statGetter{
  40. clientType: NodeType,
  41. key: r.Addr,
  42. poolSize: nodePoolSize,
  43. poolStats: func() *red.PoolStats {
  44. return store.PoolStats()
  45. },
  46. })
  47. return store, nil
  48. })
  49. if err != nil {
  50. return nil, err
  51. }
  52. return val.(*red.Client), nil
  53. }