pool.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. // ActiveCount returns the number of active connections in the pool.
  166. func (p *Pool) ActiveCount() int {
  167. p.mu.Lock()
  168. active := p.active
  169. p.mu.Unlock()
  170. return active
  171. }
  172. // Close releases the resources used by the pool.
  173. func (p *Pool) Close() error {
  174. p.mu.Lock()
  175. idle := p.idle
  176. p.idle.Init()
  177. p.closed = true
  178. p.active -= idle.Len()
  179. if p.cond != nil {
  180. p.cond.Broadcast()
  181. }
  182. p.mu.Unlock()
  183. for e := idle.Front(); e != nil; e = e.Next() {
  184. e.Value.(idleConn).c.Close()
  185. }
  186. return nil
  187. }
  188. // release decrements the active count and signals waiters. The caller must
  189. // hold p.mu during the call.
  190. func (p *Pool) release() {
  191. p.active -= 1
  192. if p.cond != nil {
  193. p.cond.Signal()
  194. }
  195. }
  196. // get prunes stale connections and returns a connection from the idle list or
  197. // creates a new connection.
  198. func (p *Pool) get() (Conn, error) {
  199. p.mu.Lock()
  200. // Prune stale connections.
  201. if timeout := p.IdleTimeout; timeout > 0 {
  202. for i, n := 0, p.idle.Len(); i < n; i++ {
  203. e := p.idle.Back()
  204. if e == nil {
  205. break
  206. }
  207. ic := e.Value.(idleConn)
  208. if ic.t.Add(timeout).After(nowFunc()) {
  209. break
  210. }
  211. p.idle.Remove(e)
  212. p.release()
  213. p.mu.Unlock()
  214. ic.c.Close()
  215. p.mu.Lock()
  216. }
  217. }
  218. for {
  219. // Get idle connection.
  220. for i, n := 0, p.idle.Len(); i < n; i++ {
  221. e := p.idle.Front()
  222. if e == nil {
  223. break
  224. }
  225. ic := e.Value.(idleConn)
  226. p.idle.Remove(e)
  227. test := p.TestOnBorrow
  228. p.mu.Unlock()
  229. if test == nil || test(ic.c, ic.t) == nil {
  230. return ic.c, nil
  231. }
  232. ic.c.Close()
  233. p.mu.Lock()
  234. p.release()
  235. }
  236. // Check for pool closed before dialing a new connection.
  237. if p.closed {
  238. p.mu.Unlock()
  239. return nil, errors.New("redigo: get on closed pool")
  240. }
  241. // Dial new connection if under limit.
  242. if p.MaxActive == 0 || p.active < p.MaxActive {
  243. dial := p.Dial
  244. p.active += 1
  245. p.mu.Unlock()
  246. c, err := dial()
  247. if err != nil {
  248. p.mu.Lock()
  249. p.release()
  250. p.mu.Unlock()
  251. c = nil
  252. }
  253. return c, err
  254. }
  255. if !p.Wait {
  256. p.mu.Unlock()
  257. return nil, ErrPoolExhausted
  258. }
  259. if p.cond == nil {
  260. p.cond = sync.NewCond(&p.mu)
  261. }
  262. p.cond.Wait()
  263. }
  264. }
  265. func (p *Pool) put(c Conn, forceClose bool) error {
  266. err := c.Err()
  267. p.mu.Lock()
  268. if !p.closed && err == nil && !forceClose {
  269. p.idle.PushFront(idleConn{t: nowFunc(), c: c})
  270. if p.idle.Len() > p.MaxIdle {
  271. c = p.idle.Remove(p.idle.Back()).(idleConn).c
  272. } else {
  273. c = nil
  274. }
  275. }
  276. if c == nil {
  277. if p.cond != nil {
  278. p.cond.Signal()
  279. }
  280. p.mu.Unlock()
  281. return nil
  282. }
  283. p.release()
  284. p.mu.Unlock()
  285. return c.Close()
  286. }
  287. type pooledConnection struct {
  288. p *Pool
  289. c Conn
  290. state int
  291. }
  292. var (
  293. sentinel []byte
  294. sentinelOnce sync.Once
  295. )
  296. func initSentinel() {
  297. p := make([]byte, 64)
  298. if _, err := rand.Read(p); err == nil {
  299. sentinel = p
  300. } else {
  301. h := sha1.New()
  302. io.WriteString(h, "Oops, rand failed. Use time instead.")
  303. io.WriteString(h, strconv.FormatInt(time.Now().UnixNano(), 10))
  304. sentinel = h.Sum(nil)
  305. }
  306. }
  307. func (pc *pooledConnection) Close() error {
  308. c := pc.c
  309. if _, ok := c.(errorConnection); ok {
  310. return nil
  311. }
  312. pc.c = errorConnection{errConnClosed}
  313. if pc.state&internal.MultiState != 0 {
  314. c.Send("DISCARD")
  315. pc.state &^= (internal.MultiState | internal.WatchState)
  316. } else if pc.state&internal.WatchState != 0 {
  317. c.Send("UNWATCH")
  318. pc.state &^= internal.WatchState
  319. }
  320. if pc.state&internal.SubscribeState != 0 {
  321. c.Send("UNSUBSCRIBE")
  322. c.Send("PUNSUBSCRIBE")
  323. // To detect the end of the message stream, ask the server to echo
  324. // a sentinel value and read until we see that value.
  325. sentinelOnce.Do(initSentinel)
  326. c.Send("ECHO", sentinel)
  327. c.Flush()
  328. for {
  329. p, err := c.Receive()
  330. if err != nil {
  331. break
  332. }
  333. if p, ok := p.([]byte); ok && bytes.Equal(p, sentinel) {
  334. pc.state &^= internal.SubscribeState
  335. break
  336. }
  337. }
  338. }
  339. c.Do("")
  340. pc.p.put(c, pc.state != 0)
  341. return nil
  342. }
  343. func (pc *pooledConnection) Err() error {
  344. return pc.c.Err()
  345. }
  346. func (pc *pooledConnection) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
  347. ci := internal.LookupCommandInfo(commandName)
  348. pc.state = (pc.state | ci.Set) &^ ci.Clear
  349. return pc.c.Do(commandName, args...)
  350. }
  351. func (pc *pooledConnection) Send(commandName string, args ...interface{}) error {
  352. ci := internal.LookupCommandInfo(commandName)
  353. pc.state = (pc.state | ci.Set) &^ ci.Clear
  354. return pc.c.Send(commandName, args...)
  355. }
  356. func (pc *pooledConnection) Flush() error {
  357. return pc.c.Flush()
  358. }
  359. func (pc *pooledConnection) Receive() (reply interface{}, err error) {
  360. return pc.c.Receive()
  361. }
  362. type errorConnection struct{ err error }
  363. func (ec errorConnection) Do(string, ...interface{}) (interface{}, error) { return nil, ec.err }
  364. func (ec errorConnection) Send(string, ...interface{}) error { return ec.err }
  365. func (ec errorConnection) Err() error { return ec.err }
  366. func (ec errorConnection) Close() error { return ec.err }
  367. func (ec errorConnection) Flush() error { return ec.err }
  368. func (ec errorConnection) Receive() (interface{}, error) { return nil, ec.err }