pool.go 9.2 KB

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