pool.go 6.8 KB

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