orc*_*man 6 go redis redislabs
我有一个应用程序,每秒大约400次读取和每秒100次写入redis(托管在redislabs上).该应用程序使用github.com/garyburd/redigo
包作为redis代理.
我有两个函数,它们是唯一用于读写的函数:
func getCachedVPAIDConfig(key string) chan *cachedVPAIDConfig {
c := make(chan *cachedVPAIDConfig)
go func() {
p := pool.Get()
defer p.Close()
switch p.Err() {
case nil:
item, err := redis.Bytes(p.Do("GET", key))
if err != nil {
c <- &cachedVPAIDConfig{nil, err}
return
}
c <- &cachedVPAIDConfig{item, nil}
default:
c <- &cachedVPAIDConfig{nil, p.Err()}
return
}
}()
return c
}
func setCachedVPAIDConfig(key string, j []byte) chan error {
c := make(chan error)
go func() {
p := pool.Get()
defer p.Close()
switch p.Err() {
case nil:
_, err := p.Do("SET", key, j)
if err != nil {
c <- err
return
}
c <- nil
default:
c <- p.Err()
return
}
}()
return c
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我正在使用推荐的连接池机制(http://godoc.org/github.com/garyburd/redigo/redis#Pool).
我在应用程序端点的每个http请求上调用这些函数.问题是:一旦应用程序开始获取请求,它立即开始抛出错误
dial tcp 54.160.xxx.xx:yyyy: connect: cannot assign requested address
Run Code Online (Sandbox Code Playgroud)
(54.160.xxx.xx:yyyy是redis主机)
我在redis上看到,当这种情况开始发生时,只有大约600个连接,这听起来不是很多.
我尝试使用MaxActive
设置pool
,将其设置在1000到50K之间,但结果是一样的.
有任何想法吗?
编辑
这是我的池初始化代码(执行此操作func init
):
pool = redis.Pool{
MaxActive: 1000, // note: I tried changing this to 50K, result the same
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", redisHost)
if err != nil {
return nil, err
}
if _, err := c.Do("AUTH", redisPassword); err != nil {
c.Close()
return nil, err
}
return c, err
},
}
Run Code Online (Sandbox Code Playgroud)
编辑2: 通过应用下面答案中建议的内容解决问题!
池初始化的新代码:
pool = redis.Pool{
MaxActive: 500,
MaxIdle: 500,
IdleTimeout: 5 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.DialTimeout("tcp", redisHost, 100*time.Millisecond, 100*time.Millisecond, 100*time.Millisecond)
if err != nil {
return nil, err
}
if _, err := c.Do("AUTH", redisPassword); err != nil {
c.Close()
return nil, err
}
return c, err
},
}
Run Code Online (Sandbox Code Playgroud)
这个新的init使得get和set超时由内部redigo处理,因此我不再需要在getCachedVPAIDConfig和setCachedVPAIDConfig函数上返回一个通道.这就是他们现在的样子:
func setCachedVPAIDConfig(key string, j []byte) error {
p := pool.Get()
switch p.Err() {
case nil:
_, err := p.Do("SET", key, j)
p.Close()
return err
default:
p.Close()
return p.Err()
}
}
func getCachedVPAIDConfig(key string) ([]byte, error) {
p := pool.Get()
switch p.Err() {
case nil:
item, err := redis.Bytes(p.Do("GET", key))
p.Close()
return item, err
default:
p.Close()
return nil, p.Err()
}
}
Run Code Online (Sandbox Code Playgroud)
您在发送频道后关闭了连接,如果频道阻塞了您就没有关闭连接,这将导致您看到的错误。因此,不要只是推迟,显式关闭连接。
我认为这不是问题,但无论如何都是个好主意-为与的连接设置超时DialTimeout
。
确保您具有适当的TestOnBorrow
功能来摆脱无效连接,尤其是在超时的情况下。如果连接空闲超过3秒钟,我通常会执行PING操作(该函数将空闲时间作为参数接收)
也尝试将其设置MaxIdle
为更大的数字,我记得通过增加池中的参数可以解决池化问题。