pool.go 9.8 KB

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