pool.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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 MaxActive 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.
  122. //
  123. // Deprecated: Initialize the Pool directory as shown in the example.
  124. func NewPool(newFn func() (Conn, error), maxIdle int) *Pool {
  125. return &Pool{Dial: newFn, MaxIdle: maxIdle}
  126. }
  127. // Get gets a connection. The application must close the returned connection.
  128. // This method always returns a valid connection so that applications can defer
  129. // error handling to the first use of the connection. If there is an error
  130. // getting an underlying connection, then the connection Err, Do, Send, Flush
  131. // and Receive methods return that error.
  132. func (p *Pool) Get() Conn {
  133. c, err := p.get()
  134. if err != nil {
  135. return errorConnection{err}
  136. }
  137. return &pooledConnection{p: p, c: c}
  138. }
  139. // ActiveCount returns the number of active connections in the pool.
  140. func (p *Pool) ActiveCount() int {
  141. p.mu.Lock()
  142. active := p.active
  143. p.mu.Unlock()
  144. return active
  145. }
  146. // Close releases the resources used by the pool.
  147. func (p *Pool) Close() error {
  148. p.mu.Lock()
  149. idle := p.idle
  150. p.idle.Init()
  151. p.closed = true
  152. p.active -= idle.Len()
  153. if p.cond != nil {
  154. p.cond.Broadcast()
  155. }
  156. p.mu.Unlock()
  157. for e := idle.Front(); e != nil; e = e.Next() {
  158. e.Value.(idleConn).c.Close()
  159. }
  160. return nil
  161. }
  162. // release decrements the active count and signals waiters. The caller must
  163. // hold p.mu during the call.
  164. func (p *Pool) release() {
  165. p.active -= 1
  166. if p.cond != nil {
  167. p.cond.Signal()
  168. }
  169. }
  170. // get prunes stale connections and returns a connection from the idle list or
  171. // creates a new connection.
  172. func (p *Pool) get() (Conn, error) {
  173. p.mu.Lock()
  174. // Prune stale connections.
  175. if timeout := p.IdleTimeout; timeout > 0 {
  176. for i, n := 0, p.idle.Len(); i < n; i++ {
  177. e := p.idle.Back()
  178. if e == nil {
  179. break
  180. }
  181. ic := e.Value.(idleConn)
  182. if ic.t.Add(timeout).After(nowFunc()) {
  183. break
  184. }
  185. p.idle.Remove(e)
  186. p.release()
  187. p.mu.Unlock()
  188. ic.c.Close()
  189. p.mu.Lock()
  190. }
  191. }
  192. for {
  193. // Get idle connection.
  194. for i, n := 0, p.idle.Len(); i < n; i++ {
  195. e := p.idle.Front()
  196. if e == nil {
  197. break
  198. }
  199. ic := e.Value.(idleConn)
  200. p.idle.Remove(e)
  201. test := p.TestOnBorrow
  202. p.mu.Unlock()
  203. if test == nil || test(ic.c, ic.t) == nil {
  204. return ic.c, nil
  205. }
  206. ic.c.Close()
  207. p.mu.Lock()
  208. p.release()
  209. }
  210. // Check for pool closed before dialing a new connection.
  211. if p.closed {
  212. p.mu.Unlock()
  213. return nil, errors.New("redigo: get on closed pool")
  214. }
  215. // Dial new connection if under limit.
  216. if p.MaxActive == 0 || p.active < p.MaxActive {
  217. dial := p.Dial
  218. p.active += 1
  219. p.mu.Unlock()
  220. c, err := dial()
  221. if err != nil {
  222. p.mu.Lock()
  223. p.release()
  224. p.mu.Unlock()
  225. c = nil
  226. }
  227. return c, err
  228. }
  229. if !p.Wait {
  230. p.mu.Unlock()
  231. return nil, ErrPoolExhausted
  232. }
  233. if p.cond == nil {
  234. p.cond = sync.NewCond(&p.mu)
  235. }
  236. p.cond.Wait()
  237. }
  238. }
  239. func (p *Pool) put(c Conn, forceClose bool) error {
  240. err := c.Err()
  241. p.mu.Lock()
  242. if !p.closed && err == nil && !forceClose {
  243. p.idle.PushFront(idleConn{t: nowFunc(), c: c})
  244. if p.idle.Len() > p.MaxIdle {
  245. c = p.idle.Remove(p.idle.Back()).(idleConn).c
  246. } else {
  247. c = nil
  248. }
  249. }
  250. if c == nil {
  251. if p.cond != nil {
  252. p.cond.Signal()
  253. }
  254. p.mu.Unlock()
  255. return nil
  256. }
  257. p.release()
  258. p.mu.Unlock()
  259. return c.Close()
  260. }
  261. type pooledConnection struct {
  262. p *Pool
  263. c Conn
  264. state int
  265. }
  266. var (
  267. sentinel []byte
  268. sentinelOnce sync.Once
  269. )
  270. func initSentinel() {
  271. p := make([]byte, 64)
  272. if _, err := rand.Read(p); err == nil {
  273. sentinel = p
  274. } else {
  275. h := sha1.New()
  276. io.WriteString(h, "Oops, rand failed. Use time instead.")
  277. io.WriteString(h, strconv.FormatInt(time.Now().UnixNano(), 10))
  278. sentinel = h.Sum(nil)
  279. }
  280. }
  281. func (pc *pooledConnection) Close() error {
  282. c := pc.c
  283. if _, ok := c.(errorConnection); ok {
  284. return nil
  285. }
  286. pc.c = errorConnection{errConnClosed}
  287. if pc.state&internal.MultiState != 0 {
  288. c.Send("DISCARD")
  289. pc.state &^= (internal.MultiState | internal.WatchState)
  290. } else if pc.state&internal.WatchState != 0 {
  291. c.Send("UNWATCH")
  292. pc.state &^= internal.WatchState
  293. }
  294. if pc.state&internal.SubscribeState != 0 {
  295. c.Send("UNSUBSCRIBE")
  296. c.Send("PUNSUBSCRIBE")
  297. // To detect the end of the message stream, ask the server to echo
  298. // a sentinel value and read until we see that value.
  299. sentinelOnce.Do(initSentinel)
  300. c.Send("ECHO", sentinel)
  301. c.Flush()
  302. for {
  303. p, err := c.Receive()
  304. if err != nil {
  305. break
  306. }
  307. if p, ok := p.([]byte); ok && bytes.Equal(p, sentinel) {
  308. pc.state &^= internal.SubscribeState
  309. break
  310. }
  311. }
  312. }
  313. c.Do("")
  314. pc.p.put(c, pc.state != 0)
  315. return nil
  316. }
  317. func (pc *pooledConnection) Err() error {
  318. return pc.c.Err()
  319. }
  320. func (pc *pooledConnection) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
  321. ci := internal.LookupCommandInfo(commandName)
  322. pc.state = (pc.state | ci.Set) &^ ci.Clear
  323. return pc.c.Do(commandName, args...)
  324. }
  325. func (pc *pooledConnection) Send(commandName string, args ...interface{}) error {
  326. ci := internal.LookupCommandInfo(commandName)
  327. pc.state = (pc.state | ci.Set) &^ ci.Clear
  328. return pc.c.Send(commandName, args...)
  329. }
  330. func (pc *pooledConnection) Flush() error {
  331. return pc.c.Flush()
  332. }
  333. func (pc *pooledConnection) Receive() (reply interface{}, err error) {
  334. return pc.c.Receive()
  335. }
  336. type errorConnection struct{ err error }
  337. func (ec errorConnection) Do(string, ...interface{}) (interface{}, error) { return nil, ec.err }
  338. func (ec errorConnection) Send(string, ...interface{}) error { return ec.err }
  339. func (ec errorConnection) Err() error { return ec.err }
  340. func (ec errorConnection) Close() error { return ec.err }
  341. func (ec errorConnection) Flush() error { return ec.err }
  342. func (ec errorConnection) Receive() (interface{}, error) { return nil, ec.err }