options.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. package redis
  2. import (
  3. "crypto/tls"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "net/url"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "gopkg.in/redis.v5/internal/pool"
  12. )
  13. type Options struct {
  14. // The network type, either tcp or unix.
  15. // Default is tcp.
  16. Network string
  17. // host:port address.
  18. Addr string
  19. // Dialer creates new network connection and has priority over
  20. // Network and Addr options.
  21. Dialer func() (net.Conn, error)
  22. // Optional password. Must match the password specified in the
  23. // requirepass server configuration option.
  24. Password string
  25. // Database to be selected after connecting to the server.
  26. DB int
  27. // Maximum number of retries before giving up.
  28. // Default is to not retry failed commands.
  29. MaxRetries int
  30. // Dial timeout for establishing new connections.
  31. // Default is 5 seconds.
  32. DialTimeout time.Duration
  33. // Timeout for socket reads. If reached, commands will fail
  34. // with a timeout instead of blocking.
  35. // Default is 3 seconds.
  36. ReadTimeout time.Duration
  37. // Timeout for socket writes. If reached, commands will fail
  38. // with a timeout instead of blocking.
  39. // Default is 3 seconds.
  40. WriteTimeout time.Duration
  41. // Maximum number of socket connections.
  42. // Default is 10 connections.
  43. PoolSize int
  44. // Amount of time client waits for connection if all connections
  45. // are busy before returning an error.
  46. // Default is ReadTimeout + 1 second.
  47. PoolTimeout time.Duration
  48. // Amount of time after which client closes idle connections.
  49. // Should be less than server's timeout.
  50. // Default is to not close idle connections.
  51. IdleTimeout time.Duration
  52. // Frequency of idle checks.
  53. // Default is 1 minute.
  54. // When minus value is set, then idle check is disabled.
  55. IdleCheckFrequency time.Duration
  56. // Enables read only queries on slave nodes.
  57. ReadOnly bool
  58. // TLS Config to use. When set TLS will be negotiated.
  59. TLSConfig *tls.Config
  60. }
  61. func (opt *Options) init() {
  62. if opt.Network == "" {
  63. opt.Network = "tcp"
  64. }
  65. if opt.Dialer == nil {
  66. opt.Dialer = func() (net.Conn, error) {
  67. conn, err := net.DialTimeout(opt.Network, opt.Addr, opt.DialTimeout)
  68. if opt.TLSConfig == nil || err != nil {
  69. return conn, err
  70. }
  71. t := tls.Client(conn, opt.TLSConfig)
  72. return t, t.Handshake()
  73. }
  74. }
  75. if opt.PoolSize == 0 {
  76. opt.PoolSize = 10
  77. }
  78. if opt.DialTimeout == 0 {
  79. opt.DialTimeout = 5 * time.Second
  80. }
  81. if opt.ReadTimeout == 0 {
  82. opt.ReadTimeout = 3 * time.Second
  83. } else if opt.ReadTimeout == -1 {
  84. opt.ReadTimeout = 0
  85. }
  86. if opt.WriteTimeout == 0 {
  87. opt.WriteTimeout = opt.ReadTimeout
  88. } else if opt.WriteTimeout == -1 {
  89. opt.WriteTimeout = 0
  90. }
  91. if opt.PoolTimeout == 0 {
  92. opt.PoolTimeout = opt.ReadTimeout + time.Second
  93. }
  94. if opt.IdleTimeout == 0 {
  95. opt.IdleTimeout = 5 * time.Minute
  96. }
  97. if opt.IdleCheckFrequency == 0 {
  98. opt.IdleCheckFrequency = time.Minute
  99. }
  100. }
  101. // ParseURL parses a redis URL into options that can be used to connect to redis
  102. func ParseURL(redisURL string) (*Options, error) {
  103. o := &Options{Network: "tcp"}
  104. u, err := url.Parse(redisURL)
  105. if err != nil {
  106. return nil, err
  107. }
  108. if u.Scheme != "redis" && u.Scheme != "rediss" {
  109. return nil, errors.New("invalid redis URL scheme: " + u.Scheme)
  110. }
  111. if u.User != nil {
  112. if p, ok := u.User.Password(); ok {
  113. o.Password = p
  114. }
  115. }
  116. if len(u.Query()) > 0 {
  117. return nil, errors.New("no options supported")
  118. }
  119. h, p, err := net.SplitHostPort(u.Host)
  120. if err != nil {
  121. h = u.Host
  122. }
  123. if h == "" {
  124. h = "localhost"
  125. }
  126. if p == "" {
  127. p = "6379"
  128. }
  129. o.Addr = net.JoinHostPort(h, p)
  130. f := strings.FieldsFunc(u.Path, func(r rune) bool {
  131. return r == '/'
  132. })
  133. switch len(f) {
  134. case 0:
  135. o.DB = 0
  136. case 1:
  137. if o.DB, err = strconv.Atoi(f[0]); err != nil {
  138. return nil, fmt.Errorf("invalid redis database number: %q", f[0])
  139. }
  140. default:
  141. return nil, errors.New("invalid redis URL path: " + u.Path)
  142. }
  143. if u.Scheme == "rediss" {
  144. o.TLSConfig = &tls.Config{ServerName: h}
  145. }
  146. return o, nil
  147. }
  148. func newConnPool(opt *Options) *pool.ConnPool {
  149. return pool.NewConnPool(
  150. opt.Dialer,
  151. opt.PoolSize,
  152. opt.PoolTimeout,
  153. opt.IdleTimeout,
  154. opt.IdleCheckFrequency,
  155. )
  156. }
  157. // PoolStats contains pool state information and accumulated stats.
  158. type PoolStats struct {
  159. Requests uint32 // number of times a connection was requested by the pool
  160. Hits uint32 // number of times free connection was found in the pool
  161. Timeouts uint32 // number of times a wait timeout occurred
  162. TotalConns uint32 // the number of total connections in the pool
  163. FreeConns uint32 // the number of free connections in the pool
  164. }