golang操作redis主要有两个库,go-redis和redigo。两者操作都比较简单,区别上redigo更像一个client执行各种操作都是通过Do函数去做的,redis-go对函数的封装更好,相比之下redigo操作redis显得有些繁琐。但是官方更推荐redigo,所以项目中我使用了redigo。
package redisclientimport ( "fmt" redigo "github.com/garyburd/redigo/redis")var pool *redigo.Poolfunc init() { redis_host := "127.0.0.1" redis_port := 6379 pool_size := 20 pool = redigo.NewPool(func() (redigo.Conn, error) { c, err := redigo.Dial("tcp", fmt.Sprintf("%s:%d", redis_host, redis_port)) if err != nil { return nil, err } return c, nil }, pool_size)}func Get() redigo.Conn { return pool.Get()}
package mainimport ( "redisclient" "logger" "github.com/garyburd/redigo/redis")func main() { c := redisclient.Get() //记得销毁本次链连接 defer c.Close() //写入数据 _, err := c.Do("SET", "go_key", "redigo") if err != nil { logger.Runtime().Info(map[string]interface{}{"error": err}, "error while setting") } //判断key是否存在 is_key_exit, err := redis.Bool(c.Do("EXISTS", "go_key")) if err != nil { logger.Runtime().Info(map[string]interface{}{"error": err}, "error while existing") } //获取value并转成字符串 account_balance, err := redis.String(c.Do("GET", "go_key")) if err != nil { logger.Runtime().Info(map[string]interface{}{"error": err}, "error while getting") } //删除key _, err = c.Do("DEL", "go_key") if err != nil { logger.Runtime().Info(map[string]interface{}{"error": err}, "error while deleting") } //设置key过期时间 _, err = c.Do("SET", "mykey", "superWang", "EX", "5") if err != nil { fmt.Println("redis set failed:", err) } //创建key时设置5s过期 _, err := c.Do("SET", "go_key:ex", "redigo", "EX", 5) if err != nil { logger.Runtime().Info(map[string]interface{}{"error": err}, "error while setting") } //对已有key设置5s过期时间 n, err := rs.Do("EXPIRE", "go_key", 5) if err != nil { logger.Runtime().Info(map[string]interface{}{"error": err}, "error while setting") } else if n != int64(1) { fmt.Println("failed") }}