golang操作redis主要有两个库,go-redis和redigo。
go-redis:star数更多,支持连接哨兵及集群模式的Redis
redigo:star数少一些,操作更简单
安装:go get github.com/garyburd/redigo/redis
func main() { conn,err:=redis.Dial("tcp", "localhost:6379") if err!=nil { fmt.Println("连接出错",err) return } defer conn.Close() res,err:=conn.Do("ping") fmt.Println(res) }
func main() { conn,err:=redis.Dial("tcp", "localhost:6379") if err!=nil { fmt.Println("连接出错",err) return } defer conn.Close() res,err:=conn.Do("ping") fmt.Println(res) // 1 字符串 set get //res,_=conn.Do("set","name","lqz") //fmt.Println(res) //res,_=redis.String(conn.Do("get","name")) //fmt.Println(res) //2 MSet MGet //conn.Do("MSet", "name", "刘清政", "age", 19) //r, _ := redis.Strings(conn.Do("MGet", "name", "age")) //fmt.Println(r) // 3 expire //res,err=conn.Do("expire", "name", 5) //4 lpush lpop conn.Do("lpush", "hobby", "篮球", "足球", "乒乓球") r, _ := redis.String(conn.Do("lpop", "hobby")) fmt.Println(r) // 5 hset hget conn.Do("HSet", "userinfo", "name", "lqz") r,_ = redis.String(conn.Do("HGet", "userinfo", "name")) fmt.Println(r) }
func main() { var pool *redis.Pool pool = &redis.Pool{ MaxIdle: 10, //最初的连接数量 MaxActive: 0, //连接池最大连接数量,(0表示自动定义),按需分配 IdleTimeout: 300, //连接关闭时间 300秒 (300秒不使用自动关闭) Dial: func() (redis.Conn, error) { //要连接的redis数据库 return redis.Dial("tcp", "localhost:6379") }, } conn := pool.Get() //从连接池,取一个链接 defer conn.Close() res, _ := conn.Do("ping") fmt.Println(res) }