pool.go 11 KB

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