我正在使用以下代码从我的 Go 应用程序执行 SET 和 EXPIRE。
_, err = C.Cache.Do("SETEX", key, 3600, data)
但我开始收到错误消息:使用已关闭的网络连接。我使用 Gary Burd 的 Redigo包和 RedisLabs。
我连接到 Redis 的代码是:
//Connect to cache (Redis)
cache, err := connectToCache()
if err != nil {
log.Printf("Cache connection settings are invalid")
os.Exit(1)
}
defer cache.Close()
func connectToCache() (redis.Conn, error) {
cache, err := redis.Dial("tcp", CACHE_URI)
if err != nil {
return nil, err
}
_, err = cache.Do("AUTH", CACHE_AUTH)
if err != nil {
cache.Close()
return nil, err
}
return cache, nil
}
最佳答案
您可以使用 redis.Pool
管理多个连接,检查空闲连接是否存在,并自动获取新连接。您还可以在调用新连接时自动执行 AUTH 步骤:
func newPool(server, password string) *redis.Pool {
return &redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func () (redis.Conn, error) {
c, err := redis.Dial("tcp", server)
if err != nil {
return nil, err
}
if _, err := c.Do("AUTH", password); err != nil {
c.Close()
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
}
var (
pool *redis.Pool
redisServer = flag.String("redisServer", ":6379", "")
redisPassword = flag.String("redisPassword", "", "")
)
func main() {
flag.Parse()
pool = newPool(*redisServer, *redisPassword)
...
}
关于go - SETEX 错误 - "Use of closed network connection",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34180858/