pool.go 11 KB

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