Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SETEX error - "Use of closed network connection"

Tags:

redis

go

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
}
like image 624
tommyd456 Avatar asked Dec 09 '15 14:12

tommyd456


1 Answers

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)
    ...
}
like image 81
JimB Avatar answered Oct 04 '22 18:10

JimB