gpt4 book ai didi

go - SETEX 错​​误 - "Use of closed network connection"

转载 作者:IT王子 更新时间:2023-10-29 00:55:58 35 4
gpt4 key购买 nike

我正在使用以下代码从我的 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/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com