pool.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. "container/list"
  18. "crypto/rand"
  19. "crypto/sha1"
  20. "errors"
  21. "io"
  22. "strconv"
  23. "sync"
  24. "time"
  25. )
  26. var nowFunc = time.Now // for testing
  27. // ErrPoolExhausted is returned from a pool connection method (Do, Send,
  28. // Receive, Flush, Err) when the maximum number of database connections in the
  29. // pool has been reached.
  30. var ErrPoolExhausted = errors.New("redigo: connection pool exhausted")
  31. var (
  32. errPoolClosed = errors.New("redigo: connection pool closed")
  33. errConnClosed = errors.New("redigo: connection closed")
  34. )
  35. // Pool maintains a pool of connections. The application calls the Get method
  36. // to get a connection from the pool and the connection's Close method to
  37. // return the connection's resources to the pool.
  38. //
  39. // The following example shows how to use a pool in a web application. The
  40. // application creates a pool at application startup and makes it available to
  41. // request handlers using a global variable.
  42. //
  43. // func newPool(server, password string) *redis.Pool {
  44. // return &redis.Pool{
  45. // MaxIdle: 3,
  46. // IdleTimeout: 240 * time.Second,
  47. // Dial: func () (redis.Conn, error) {
  48. // c, err := redis.Dial("tcp", server)
  49. // if err != nil {
  50. // return nil, err
  51. // }
  52. // if _, err := c.Do("AUTH", password); err != nil {
  53. // c.Close()
  54. // return nil, err
  55. // }
  56. // return c, err
  57. // },
  58. // TestOnBorrow: func(c redis.Conn, t time.Time) error {
  59. // _, err := c.Do("PING")
  60. // return err
  61. // },
  62. // }
  63. // }
  64. //
  65. // var (
  66. // pool *redis.Pool
  67. // redisServer = flag.String("redisServer", ":6379", "")
  68. // redisPassword = flag.String("redisPassword", "", "")
  69. // )
  70. //
  71. // func main() {
  72. // flag.Parse()
  73. // pool = newPool(*redisServer, *redisPassword)
  74. // ...
  75. // }
  76. //
  77. // A request handler gets a connection from the pool and closes the connection
  78. // when the handler is done:
  79. //
  80. // func serveHome(w http.ResponseWriter, r *http.Request) {
  81. // conn := pool.Get()
  82. // defer conn.Close()
  83. // ....
  84. // }
  85. //
  86. type Pool struct {
  87. // Dial is an application supplied function for creating and configuring a
  88. // connection
  89. Dial func() (Conn, error)
  90. // TestOnBorrow is an optional application supplied function for checking
  91. // the health of an idle connection before the connection is used again by
  92. // the application. Argument t is the time that the connection was returned
  93. // to the pool. If the function returns an error, then the connection is
  94. // closed.
  95. TestOnBorrow func(c Conn, t time.Time) error
  96. // Maximum number of idle connections in the pool.
  97. MaxIdle int
  98. // Maximum number of connections allocated by the pool at a given time.
  99. // When zero, there is no limit on the number of connections in the pool.
  100. MaxActive int
  101. // Close connections after remaining idle for this duration. If the value
  102. // is zero, then idle connections are not closed. Applications should set
  103. // the timeout to a value less than the server's timeout.
  104. IdleTimeout time.Duration
  105. // mu protects fields defined below.
  106. mu sync.Mutex
  107. closed bool
  108. active int
  109. // Stack of idleConn with most recently used at the front.
  110. idle list.List
  111. }
  112. type idleConn struct {
  113. c Conn
  114. t time.Time
  115. }
  116. // NewPool creates a new pool. This function is deprecated. Applications should
  117. // initialize the Pool fields directly as shown in example.
  118. func NewPool(newFn func() (Conn, error), maxIdle int) *Pool {
  119. return &Pool{Dial: newFn, MaxIdle: maxIdle}
  120. }
  121. // Get gets a connection. The application must close the returned connection.
  122. // This method always returns a valid connection so that applications can defer
  123. // error handling to the first use of the connection. If there is an error
  124. // getting an underlying connection, then the connection Err, Do, Send, Flush
  125. // and Receive methods return that error.
  126. func (p *Pool) Get() Conn {
  127. c, err := p.get()
  128. if err != nil {
  129. return errorConnection{err}
  130. }
  131. return &pooledConnection{p: p, c: c}
  132. }
  133. // ActiveCount returns the number of active connections in the pool.
  134. func (p *Pool) ActiveCount() int {
  135. p.mu.Lock()
  136. active := p.active
  137. p.mu.Unlock()
  138. return active
  139. }
  140. // Close releases the resources used by the pool.
  141. func (p *Pool) Close() error {
  142. p.mu.Lock()
  143. idle := p.idle
  144. p.idle.Init()
  145. p.closed = true
  146. p.active -= idle.Len()
  147. p.mu.Unlock()
  148. for e := idle.Front(); e != nil; e = e.Next() {
  149. e.Value.(idleConn).c.Close()
  150. }
  151. return nil
  152. }
  153. // get prunes stale connections and returns a connection from the idle list or
  154. // creates a new connection.
  155. func (p *Pool) get() (Conn, error) {
  156. p.mu.Lock()
  157. if p.closed {
  158. p.mu.Unlock()
  159. return nil, errors.New("redigo: get on closed pool")
  160. }
  161. // Prune stale connections.
  162. if timeout := p.IdleTimeout; timeout > 0 {
  163. for i, n := 0, p.idle.Len(); i < n; i++ {
  164. e := p.idle.Back()
  165. if e == nil {
  166. break
  167. }
  168. ic := e.Value.(idleConn)
  169. if ic.t.Add(timeout).After(nowFunc()) {
  170. break
  171. }
  172. p.idle.Remove(e)
  173. p.active -= 1
  174. p.mu.Unlock()
  175. ic.c.Close()
  176. p.mu.Lock()
  177. }
  178. }
  179. // Get idle connection.
  180. for i, n := 0, p.idle.Len(); i < n; i++ {
  181. e := p.idle.Front()
  182. if e == nil {
  183. break
  184. }
  185. ic := e.Value.(idleConn)
  186. p.idle.Remove(e)
  187. test := p.TestOnBorrow
  188. p.mu.Unlock()
  189. if test == nil || test(ic.c, ic.t) == nil {
  190. return ic.c, nil
  191. }
  192. ic.c.Close()
  193. p.mu.Lock()
  194. p.active -= 1
  195. }
  196. if p.MaxActive > 0 && p.active >= p.MaxActive {
  197. p.mu.Unlock()
  198. return nil, ErrPoolExhausted
  199. }
  200. // No idle connection, create new.
  201. dial := p.Dial
  202. p.active += 1
  203. p.mu.Unlock()
  204. c, err := dial()
  205. if err != nil {
  206. p.mu.Lock()
  207. p.active -= 1
  208. p.mu.Unlock()
  209. c = nil
  210. }
  211. return c, err
  212. }
  213. func (p *Pool) put(c Conn, forceClose bool) error {
  214. if c.Err() == nil && !forceClose {
  215. p.mu.Lock()
  216. if !p.closed {
  217. p.idle.PushFront(idleConn{t: nowFunc(), c: c})
  218. if p.idle.Len() > p.MaxIdle {
  219. c = p.idle.Remove(p.idle.Back()).(idleConn).c
  220. } else {
  221. c = nil
  222. }
  223. }
  224. p.mu.Unlock()
  225. }
  226. if c != nil {
  227. p.mu.Lock()
  228. p.active -= 1
  229. p.mu.Unlock()
  230. return c.Close()
  231. }
  232. return nil
  233. }
  234. type pooledConnection struct {
  235. p *Pool
  236. c Conn
  237. state int
  238. }
  239. var (
  240. sentinel []byte
  241. sentinelOnce sync.Once
  242. )
  243. func initSentinel() {
  244. p := make([]byte, 64)
  245. if _, err := rand.Read(p); err == nil {
  246. sentinel = p
  247. } else {
  248. h := sha1.New()
  249. io.WriteString(h, "Oops, rand failed. Use time instead.")
  250. io.WriteString(h, strconv.FormatInt(time.Now().UnixNano(), 10))
  251. sentinel = h.Sum(nil)
  252. }
  253. }
  254. func (pc *pooledConnection) Close() error {
  255. c := pc.c
  256. if _, ok := c.(errorConnection); ok {
  257. return nil
  258. }
  259. pc.c = errorConnection{errConnClosed}
  260. if pc.state&multiState != 0 {
  261. c.Send("DISCARD")
  262. pc.state &^= (multiState | watchState)
  263. } else if pc.state&watchState != 0 {
  264. c.Send("UNWATCH")
  265. pc.state &^= watchState
  266. }
  267. if pc.state&subscribeState != 0 {
  268. c.Send("UNSUBSCRIBE")
  269. c.Send("PUNSUBSCRIBE")
  270. // To detect the end of the message stream, ask the server to echo
  271. // a sentinel value and read until we see that value.
  272. sentinelOnce.Do(initSentinel)
  273. c.Send("ECHO", sentinel)
  274. c.Flush()
  275. for {
  276. p, err := c.Receive()
  277. if err != nil {
  278. break
  279. }
  280. if p, ok := p.([]byte); ok && bytes.Equal(p, sentinel) {
  281. pc.state &^= subscribeState
  282. break
  283. }
  284. }
  285. }
  286. c.Do("")
  287. pc.p.put(c, pc.state != 0)
  288. return nil
  289. }
  290. func (pc *pooledConnection) Err() error {
  291. return pc.c.Err()
  292. }
  293. func (pc *pooledConnection) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
  294. ci := lookupCommandInfo(commandName)
  295. pc.state = (pc.state | ci.set) &^ ci.clear
  296. return pc.c.Do(commandName, args...)
  297. }
  298. func (pc *pooledConnection) Send(commandName string, args ...interface{}) error {
  299. ci := lookupCommandInfo(commandName)
  300. pc.state = (pc.state | ci.set) &^ ci.clear
  301. return pc.c.Send(commandName, args...)
  302. }
  303. func (pc *pooledConnection) Flush() error {
  304. return pc.c.Flush()
  305. }
  306. func (pc *pooledConnection) Receive() (reply interface{}, err error) {
  307. return pc.c.Receive()
  308. }
  309. type errorConnection struct{ err error }
  310. func (ec errorConnection) Do(string, ...interface{}) (interface{}, error) { return nil, ec.err }
  311. func (ec errorConnection) Send(string, ...interface{}) error { return ec.err }
  312. func (ec errorConnection) Err() error { return ec.err }
  313. func (ec errorConnection) Close() error { return ec.err }
  314. func (ec errorConnection) Flush() error { return ec.err }
  315. func (ec errorConnection) Receive() (interface{}, error) { return nil, ec.err }