pool.go 8.7 KB

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