redigo代码分析-pool

来源:互联网 发布:排列三九宫图算法 编辑:程序博客网 时间:2024/05/21 10:40

redis连接池获取一个连接,在获取连接之前,先把超时的空闲连接断开

// get prunes stale connections and returns a connection from the idle list or

// creates a new connection.
func (p *Pool) get() (Conn, error) {
    p.mu.Lock()


    // Prune stale connections.


    if timeout := p.IdleTimeout; timeout > 0 { 
        for i, n := 0, p.idle.Len(); i < n; i++ {
            e := p.idle.Back()
            if e == nil {
                break
            }   
            ic := e.Value.(idleConn)
            if ic.t.Add(timeout).After(nowFunc()) {
                break
            }   
            p.idle.Remove(e)
            p.release()
            p.mu.Unlock()
            ic.c.Close()
            p.mu.Lock()
        }   

    }

   ......

}

对空闲list遍历,如果该连接在失效时间(timeout)内,则认为是可用连接,否则当做失效连接,删除。找到第一个可用连接即可返回。

注意: 这里是从后向前遍历,找到第一个可用的就退出。在下面的循环中(没有列出,省略了),是从前面获取一个,这也是返回最近使用过的连接。因为在put的时候,是放在list的前面的。

0 0
原创粉丝点击