Go与Redis连接池的那些事儿~一、什么是连接池,连接池有什么用 先看看别人是怎么介绍连接池的吧: 连接池基本的思想是在系统初始化的时候,将数据库连接作为对象存储在内存中,当用户需要访问数据库时,并非建立一个新的连接,而是从连接池中取出一个已建立的空闲连接对象。使用完毕后,用户也并非将连接关闭,而是将连接放回连接池中,以供下一个请求访问使用。而连接的建立、断开都由连接池自身来管理。同时,还可以通过设置连接池的参数来控制连接池中的初始连接数、连接的上下限数以及每个连接的最大使用次数、最大空闲时间等等。也可以通过其自身的管理机制来监视数据库连接的数量、使用情况等。下面我来简单解释一下,因为每次Redis客户端连接Redis服务端都需要一段时间,而处理各种操作的时间很多时候都很短,如果每次进行各种操作时都需要重新连接Redis,那么就会浪费大量时间。因此Redis引入连接池,连接池可以实现建立多个客户端连接而不释放,避免浪费IO资源,不使用的时候就放在连接池,这样就减少了连接数据库所需要的时间,提高效率。 连接池就是建一个池子和一定量的管道。每次当管道被取尽时,就不能继续消耗IO资源了,这样就保证了IO资源不会耗尽。 二、代码展示package main
import (
"fmt"
"github.com/garyburd/redigo/redis"
"strconv"
"time"
)
func main() {
pool := &redis.Pool{
// Maximum number of connections allocated by the pool at a given time.
// When zero, there is no limit on the number of connections in the pool.
//最大活跃连接数,0代表无限
MaxActive: 888,
//最大闲置连接数
// Maximum number of idle connections in the pool.
MaxIdle: 20,
//闲置连接的超时时间
// Close connections after remaining idle for this duration. If the value
// is zero, then idle connections are not closed. Applications should set
// the timeout to a value less than the server's timeout.
IdleTimeout: time.Second * 100,
//定义拨号获得连接的函数
// Dial is an application supplied function for creating and configuring a
// connection.
//
// The connection returned from Dial must not be in a special state
// (subscribed to pubsub channel, transaction started, ...).
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp","127.0.0.1:6379"),
}
}
//延迟关闭连接池
defer pool.Close()
//IO并发连接
for i:=0;i |