pool.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. // Copyright 2012 Gary Burd
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package redis
  15. import (
  16. "bytes"
  17. "context"
  18. "crypto/rand"
  19. "crypto/sha1"
  20. "errors"
  21. "io"
  22. "strconv"
  23. "sync"
  24. "time"
  25. "go-common/library/container/pool"
  26. "go-common/library/net/trace"
  27. xtime "go-common/library/time"
  28. )
  29. var beginTime, _ = time.Parse("2006-01-02 15:04:05", "2006-01-02 15:04:05")
  30. var (
  31. errConnClosed = errors.New("redigo: connection closed")
  32. )
  33. // Pool .
  34. type Pool struct {
  35. *pool.Slice
  36. // config
  37. c *Config
  38. }
  39. // Config client settings.
  40. type Config struct {
  41. *pool.Config
  42. Name string // redis name, for trace
  43. Proto string
  44. Addr string
  45. Auth string
  46. DialTimeout xtime.Duration
  47. ReadTimeout xtime.Duration
  48. WriteTimeout xtime.Duration
  49. }
  50. // NewPool creates a new pool.
  51. func NewPool(c *Config, options ...DialOption) (p *Pool) {
  52. if c.DialTimeout <= 0 || c.ReadTimeout <= 0 || c.WriteTimeout <= 0 {
  53. panic("must config redis timeout")
  54. }
  55. p1 := pool.NewSlice(c.Config)
  56. cnop := DialConnectTimeout(time.Duration(c.DialTimeout))
  57. options = append(options, cnop)
  58. rdop := DialReadTimeout(time.Duration(c.ReadTimeout))
  59. options = append(options, rdop)
  60. wrop := DialWriteTimeout(time.Duration(c.WriteTimeout))
  61. options = append(options, wrop)
  62. auop := DialPassword(c.Auth)
  63. options = append(options, auop)
  64. // new pool
  65. p1.New = func(ctx context.Context) (io.Closer, error) {
  66. conn, err := Dial(c.Proto, c.Addr, options...)
  67. if err != nil {
  68. return nil, err
  69. }
  70. return &traceConn{Conn: conn, connTags: []trace.Tag{trace.TagString(trace.TagPeerAddress, c.Addr)}}, nil
  71. }
  72. p = &Pool{Slice: p1, c: c}
  73. return
  74. }
  75. // Get gets a connection. The application must close the returned connection.
  76. // This method always returns a valid connection so that applications can defer
  77. // error handling to the first use of the connection. If there is an error
  78. // getting an underlying connection, then the connection Err, Do, Send, Flush
  79. // and Receive methods return that error.
  80. func (p *Pool) Get(ctx context.Context) Conn {
  81. c, err := p.Slice.Get(ctx)
  82. if err != nil {
  83. return errorConnection{err}
  84. }
  85. c1, _ := c.(Conn)
  86. return &pooledConnection{p: p, c: c1.WithContext(ctx), ctx: ctx, now: beginTime}
  87. }
  88. // Close releases the resources used by the pool.
  89. func (p *Pool) Close() error {
  90. return p.Slice.Close()
  91. }
  92. type pooledConnection struct {
  93. p *Pool
  94. c Conn
  95. state int
  96. now time.Time
  97. cmds []string
  98. ctx context.Context
  99. }
  100. var (
  101. sentinel []byte
  102. sentinelOnce sync.Once
  103. )
  104. func initSentinel() {
  105. p := make([]byte, 64)
  106. if _, err := rand.Read(p); err == nil {
  107. sentinel = p
  108. } else {
  109. h := sha1.New()
  110. io.WriteString(h, "Oops, rand failed. Use time instead.")
  111. io.WriteString(h, strconv.FormatInt(time.Now().UnixNano(), 10))
  112. sentinel = h.Sum(nil)
  113. }
  114. }
  115. func (pc *pooledConnection) Close() error {
  116. c := pc.c
  117. if _, ok := c.(errorConnection); ok {
  118. return nil
  119. }
  120. pc.c = errorConnection{errConnClosed}
  121. if pc.state&MultiState != 0 {
  122. c.Send("DISCARD")
  123. pc.state &^= (MultiState | WatchState)
  124. } else if pc.state&WatchState != 0 {
  125. c.Send("UNWATCH")
  126. pc.state &^= WatchState
  127. }
  128. if pc.state&SubscribeState != 0 {
  129. c.Send("UNSUBSCRIBE")
  130. c.Send("PUNSUBSCRIBE")
  131. // To detect the end of the message stream, ask the server to echo
  132. // a sentinel value and read until we see that value.
  133. sentinelOnce.Do(initSentinel)
  134. c.Send("ECHO", sentinel)
  135. c.Flush()
  136. for {
  137. p, err := c.Receive()
  138. if err != nil {
  139. break
  140. }
  141. if p, ok := p.([]byte); ok && bytes.Equal(p, sentinel) {
  142. pc.state &^= SubscribeState
  143. break
  144. }
  145. }
  146. }
  147. _, err := c.Do("")
  148. pc.p.Slice.Put(context.Background(), c, pc.state != 0 || c.Err() != nil)
  149. return err
  150. }
  151. func (pc *pooledConnection) Err() error {
  152. return pc.c.Err()
  153. }
  154. func key(args interface{}) (key string) {
  155. keys, _ := args.([]interface{})
  156. if len(keys) > 0 {
  157. key, _ = keys[0].(string)
  158. }
  159. return
  160. }
  161. func (pc *pooledConnection) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
  162. ci := LookupCommandInfo(commandName)
  163. pc.state = (pc.state | ci.Set) &^ ci.Clear
  164. reply, err = pc.c.Do(commandName, args...)
  165. return
  166. }
  167. func (pc *pooledConnection) Send(commandName string, args ...interface{}) (err error) {
  168. ci := LookupCommandInfo(commandName)
  169. pc.state = (pc.state | ci.Set) &^ ci.Clear
  170. if pc.now.Equal(beginTime) {
  171. // mark first send time
  172. pc.now = time.Now()
  173. }
  174. pc.cmds = append(pc.cmds, commandName)
  175. return pc.c.Send(commandName, args...)
  176. }
  177. func (pc *pooledConnection) Flush() error {
  178. return pc.c.Flush()
  179. }
  180. func (pc *pooledConnection) Receive() (reply interface{}, err error) {
  181. reply, err = pc.c.Receive()
  182. if len(pc.cmds) > 0 {
  183. pc.cmds = pc.cmds[1:]
  184. }
  185. return
  186. }
  187. func (pc *pooledConnection) WithContext(ctx context.Context) Conn {
  188. pc.ctx = ctx
  189. return pc
  190. }
  191. type errorConnection struct{ err error }
  192. func (ec errorConnection) Do(string, ...interface{}) (interface{}, error) {
  193. return nil, ec.err
  194. }
  195. func (ec errorConnection) Send(string, ...interface{}) error { return ec.err }
  196. func (ec errorConnection) Err() error { return ec.err }
  197. func (ec errorConnection) Close() error { return ec.err }
  198. func (ec errorConnection) Flush() error { return ec.err }
  199. func (ec errorConnection) Receive() (interface{}, error) { return nil, ec.err }
  200. func (ec errorConnection) WithContext(context.Context) Conn { return ec }