go - Sharing Redis settings across routes -
i have number of routes in routes.go file , call redis database. i'm wondering how can avoid calling dial , auth calls in every route.
i've tried setting variables outside functions this:
var ( c, err = redis.dial("tcp", address) _, err = c.do("auth", "testing") ) but compiler doesn't err being used twice.
first, use var declaring variables. can't run code outside of functions, there's no use in trying create connections inside var statement. use init() if need run @ startup.
the redis connections can't used concurrent requests. if want share redis connection across multiple routes, need have safe method concurrent use. in case of github.com/garyburd/redigo/redis want use pool. can auth call inside dial function, returning ready connection each time.
var redispool *redis.pool func init() { redispool = &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 }, } } then each time need connection, 1 pool, , return when you're done.
conn := redispool.get() // conn.close() returns connection pool defer conn.close() if err := conn.err(); err != nil { // conn.err() have connection or dial related errors return nil, err }
Comments
Post a Comment