pool.go 10 KB

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