pool.go 12 KB

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