github.com/apremalal/vamps-core@v1.0.1-0.20161221121535-d430b56ec174/redis/redis_client.go (about) 1 package redis 2 3 import ( 4 "time" 5 6 "github.com/apremalal/redigo/redis" 7 "github.com/vedicsoft/vamps-core/commons" 8 ) 9 10 type RedisCli struct { 11 conn redis.Conn 12 } 13 14 var ( 15 pool *redis.Pool 16 ) 17 18 func init() { 19 pool = newPool(commons.ServerConfigurations.RedisConfigs.Address, commons.ServerConfigurations.RedisConfigs.Password) 20 } 21 22 func newPool(server, password string) *redis.Pool { 23 return &redis.Pool{ 24 MaxIdle: 3, 25 IdleTimeout: 240 * time.Second, 26 Dial: func() (redis.Conn, error) { 27 c, err := redis.Dial("tcp", server) 28 if err != nil { 29 return nil, err 30 } 31 if _, err := c.Do("AUTH", password); err != nil { 32 c.Close() 33 return nil, err 34 } 35 return c, err 36 }, 37 TestOnBorrow: func(c redis.Conn, t time.Time) error { 38 _, err := c.Do("PING") 39 return err 40 }, 41 } 42 } 43 44 func SetValue(key string, value string, expiration ...interface{}) error { 45 redisConnection := pool.Get() 46 defer redisConnection.Close() 47 _, err := redisConnection.Do("SET", key, value) 48 49 if err == nil && expiration != nil { 50 redisConnection.Do("EXPIRE", key, expiration[0]) 51 } 52 return err 53 } 54 55 func GetValue(key string) (interface{}, error) { 56 redisConnection := pool.Get() 57 defer redisConnection.Close() 58 return redisConnection.Do("GET", key) 59 }