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

标签 go redis

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

相关文章:

go - 如何使用 reflect.DeepEqual() 将指针的值与其类型的零值进行比较?

node.js - AWS Elastic Cache 是否支持 Redis 集群上的 Pub/Sub?

PHP REDIS/MYSQL,并发连接问题

for-loop - 如果 panic 发生,恢复并继续 for 循环 Golang

mysql - 无法在 Google App Engine 中使用 MySQL Go Driver

javascript - 如何在 Redis 中进行持久化存储?

logging - Sidekiq 记录 Redis 查询

ruby-on-rails - 无法在同一 VPC 上将 aws redis 与 ec2 连接

Go:安全地将整数转换为 Protocol Buffer 枚举值的最佳实践

caching - 如何将此缓存项转换回 map slice ?