pool.go 8.6 KB

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