douzi7890 2015-12-09 14:09
浏览 161
已采纳

SETEX错误-“使用封闭的网络连接”

I'm using the following code to execute a SET and EXPIRE from my Go app.

_, err = C.Cache.Do("SETEX", key, 3600, data)

but I've started to get an error: Use of closed network connection. I use Gary Burd's Redigo package and RedisLabs.

My code to connect to Redis is:

//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
}
  • 写回答

1条回答 默认 最新

  • dtvpe4837413 2015-12-09 14:49
    关注

    You can use a redis.Pool to manage multiple connections, check that idle connections are alive, and get new connections automatically. You can also do the AUTH step automatically when dialing a new connection:

    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)
        ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应