pool.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. "container/list"
  17. "errors"
  18. "sync"
  19. "time"
  20. )
  21. var nowFunc = time.Now // for testing
  22. // ErrPoolExhausted is returned from pool connection methods when the maximum
  23. // number of database connections in the pool has been reached.
  24. var ErrPoolExhausted = errors.New("redigo: connection pool exhausted")
  25. var errPoolClosed = errors.New("redigo: connection pool closed")
  26. // Pool maintains a pool of connections. The application calls the Get method
  27. // to get a connection from the pool and the connection's Close method to
  28. // return the connection's resources to the pool.
  29. //
  30. // The following example shows how to use a pool in a web application. The
  31. // application creates a pool at application startup and makes it available to
  32. // request handlers, possibly using a global variable:
  33. //
  34. // var server string // host:port of server
  35. // var password string
  36. // ...
  37. //
  38. // pool = &redis.Pool{
  39. // MaxIdle: 3,
  40. // IdleTimeout: 240 * time.Second,
  41. // Dial: func () (redis.Conn, error) {
  42. // c, err := redis.Dial("tcp", server)
  43. // if err != nil {
  44. // return nil, err
  45. // }
  46. // if _, err := c.Do("AUTH", password); err != nil {
  47. // c.Close()
  48. // return nil, err
  49. // }
  50. // return c, err
  51. // },
  52. // TestOnBorrow: func(c redis.Conn, t time.Time) error {
  53. // _, err := c.Do("PING")
  54. // return err
  55. // },
  56. // }
  57. //
  58. // This pool has a maximum of three connections to the server specified by the
  59. // variable "server". Each connection is authenticated using a password.
  60. //
  61. // A request handler gets a connection from the pool and closes the connection
  62. // when the handler is done:
  63. //
  64. // conn := pool.Get()
  65. // defer conn.Close()
  66. // // do something with the connection
  67. type Pool struct {
  68. // Dial is an application supplied function for creating new connections.
  69. Dial func() (Conn, error)
  70. // TestOnBorrow is an optional application supplied function for checking
  71. // the health of an idle connection before the connection is used again by
  72. // the application. Argument t is the time that the connection was returned
  73. // to the pool. If the function returns an error, then the connection is
  74. // closed.
  75. TestOnBorrow func(c Conn, t time.Time) error
  76. // Maximum number of idle connections in the pool.
  77. MaxIdle int
  78. // Maximum number of connections allocated by the pool at a given time.
  79. // When zero, there is no limit on the number of connections in the pool.
  80. MaxActive int
  81. // Close connections after remaining idle for this duration. If the value
  82. // is zero, then idle connections are not closed. Applications should set
  83. // the timeout to a value less than the server's timeout.
  84. IdleTimeout time.Duration
  85. // mu protects fields defined below.
  86. mu sync.Mutex
  87. closed bool
  88. active int
  89. // Stack of idleConn with most recently used at the front.
  90. idle list.List
  91. }
  92. type idleConn struct {
  93. c Conn
  94. t time.Time
  95. }
  96. // NewPool returns a pool that uses newPool to create connections as needed.
  97. // The pool keeps a maximum of maxIdle idle connections.
  98. func NewPool(newFn func() (Conn, error), maxIdle int) *Pool {
  99. return &Pool{Dial: newFn, MaxIdle: maxIdle}
  100. }
  101. // Get gets a connection from the pool.
  102. func (p *Pool) Get() Conn {
  103. return &pooledConnection{p: p}
  104. }
  105. // ActiveCount returns the number of active connections in the pool.
  106. func (p *Pool) ActiveCount() int {
  107. p.mu.Lock()
  108. active := p.active
  109. p.mu.Unlock()
  110. return active
  111. }
  112. // Close releases the resources used by the pool.
  113. func (p *Pool) Close() error {
  114. p.mu.Lock()
  115. idle := p.idle
  116. p.idle.Init()
  117. p.closed = true
  118. p.active -= idle.Len()
  119. p.mu.Unlock()
  120. for e := idle.Front(); e != nil; e = e.Next() {
  121. e.Value.(idleConn).c.Close()
  122. }
  123. return nil
  124. }
  125. // get prunes stale connections and returns a connection from the idle list or
  126. // creates a new connection.
  127. func (p *Pool) get() (Conn, error) {
  128. p.mu.Lock()
  129. if p.closed {
  130. p.mu.Unlock()
  131. return nil, errors.New("redigo: get on closed pool")
  132. }
  133. // Prune stale connections.
  134. if timeout := p.IdleTimeout; timeout > 0 {
  135. for i, n := 0, p.idle.Len(); i < n; i++ {
  136. e := p.idle.Back()
  137. if e == nil {
  138. break
  139. }
  140. ic := e.Value.(idleConn)
  141. if ic.t.Add(timeout).After(nowFunc()) {
  142. break
  143. }
  144. p.idle.Remove(e)
  145. p.active -= 1
  146. p.mu.Unlock()
  147. ic.c.Close()
  148. p.mu.Lock()
  149. }
  150. }
  151. // Get idle connection.
  152. for i, n := 0, p.idle.Len(); i < n; i++ {
  153. e := p.idle.Front()
  154. if e == nil {
  155. break
  156. }
  157. ic := e.Value.(idleConn)
  158. p.idle.Remove(e)
  159. test := p.TestOnBorrow
  160. p.mu.Unlock()
  161. if test == nil || test(ic.c, ic.t) == nil {
  162. return ic.c, nil
  163. }
  164. ic.c.Close()
  165. p.mu.Lock()
  166. p.active -= 1
  167. }
  168. if p.MaxActive > 0 && p.active >= p.MaxActive {
  169. p.mu.Unlock()
  170. return nil, ErrPoolExhausted
  171. }
  172. // No idle connection, create new.
  173. dial := p.Dial
  174. p.active += 1
  175. p.mu.Unlock()
  176. c, err := dial()
  177. if err != nil {
  178. p.mu.Lock()
  179. p.active -= 1
  180. p.mu.Unlock()
  181. c = nil
  182. }
  183. return c, err
  184. }
  185. func (p *Pool) put(c Conn) error {
  186. if c.Err() == nil {
  187. p.mu.Lock()
  188. if !p.closed {
  189. p.idle.PushFront(idleConn{t: nowFunc(), c: c})
  190. if p.idle.Len() > p.MaxIdle {
  191. c = p.idle.Remove(p.idle.Back()).(idleConn).c
  192. } else {
  193. c = nil
  194. }
  195. }
  196. p.mu.Unlock()
  197. }
  198. if c != nil {
  199. p.mu.Lock()
  200. p.active -= 1
  201. p.mu.Unlock()
  202. return c.Close()
  203. }
  204. return nil
  205. }
  206. type pooledConnection struct {
  207. c Conn
  208. err error
  209. p *Pool
  210. }
  211. func (c *pooledConnection) get() error {
  212. if c.err == nil && c.c == nil {
  213. c.c, c.err = c.p.get()
  214. }
  215. return c.err
  216. }
  217. func (c *pooledConnection) Close() (err error) {
  218. if c.c != nil {
  219. c.c.Do("")
  220. c.p.put(c.c)
  221. c.c = nil
  222. c.err = errPoolClosed
  223. }
  224. return err
  225. }
  226. func (c *pooledConnection) Err() error {
  227. if err := c.get(); err != nil {
  228. return err
  229. }
  230. return c.c.Err()
  231. }
  232. func (c *pooledConnection) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
  233. if err := c.get(); err != nil {
  234. return nil, err
  235. }
  236. return c.c.Do(commandName, args...)
  237. }
  238. func (c *pooledConnection) Send(commandName string, args ...interface{}) error {
  239. if err := c.get(); err != nil {
  240. return err
  241. }
  242. return c.c.Send(commandName, args...)
  243. }
  244. func (c *pooledConnection) Flush() error {
  245. if err := c.get(); err != nil {
  246. return err
  247. }
  248. return c.c.Flush()
  249. }
  250. func (c *pooledConnection) Receive() (reply interface{}, err error) {
  251. if err := c.get(); err != nil {
  252. return nil, err
  253. }
  254. return c.c.Receive()
  255. }