options.go 4.7 KB

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