This is a creation in Article, where the information may have evolved or changed.
In a Golang project, to frequently use Redis (or other similar nosql) to access data, it's a good idea to use Redigo's own pool to manage connections.
Otherwise, whenever you want to operate Redis, the connection is established, and then shut down, causing a large number of connections to be in the time_wait State (the Redis connection is essentially TCP).
Note:time_wait, also known as the TCP semi-connected state, will continue to occupy the local port.
The following is the Golang implementation of the Redis connection pool:
Import ("Github.com/garyburd/redigo/redis" "Github.com/astaxie/beego" "Time") var (//define constant Redisclient *redis. Poolredis_host stringredis_db int) func init () {//Gets the Redis IP from the configuration file and Dbredis_host = Beego. Appconfig.string ("Redis.host") redis_db, _ = Beego. Appconfig.int ("redis.db")//Establish connection pool redisclient = &redis. pool{//gets Maxidle and maxactive from the configuration file, and does not take the following default value Maxidle: beego. Appconfig.defaultint ("Redis.maxidle", 1), maxactive: beego. Appconfig.defaultint ("Redis.maxactive", "ten"), idletimeout:180 * time. Second,dial:func () (Redis. Conn, error) {c, err: = Redis. Dial ("TCP", Redis_host) if err! = Nil {return nil, err}//select DBC. Do ("select", redis_db) return C, nil},}}
among them, the explanations of the parameters are as follows:
maxidle: Maximum number of idle connections, means that you can keep n idle even without a Redis connection connected without being cleared, ready to be on standby.
Maxactive: Maximum number of active connections, indicating a maximum of n connections at a time
IdleTimeout: Maximum idle connection wait time after which idle connection is closed
Dial: Establishing a connection
Code when you use a connection pool:
Get the connection from the pool RC: = Redisclient.get ()//after use, put the connection back into the connection pool defer RC. Close ()
The above is the use of the connection pool, very simple.