您的位置:首页 > 数据库 > Redis

golang操作redis

weixin_41571449 2018-03-03 17:05 14 查看
golang操作redis主要有两个库, github地址

redigo

redis

区别是redigo类似于一个redis_cli的client,执行各项命令都用Do函数去做.

redis则将各种操作封装成函数了

个人倾向于redis,redigo执行命令过于繁琐了,初接触用Do方法执行命令容易出错,比如range里面的返回的整型数都要用string类型的,让我觉得有些困扰

起client

redigo

wujingcideMacBook-Pro:redigo wujingci$ cat redigo.go
package main
import (
"fmt"
"github.com/garyburd/redigo/redis"
"time"
)

func main() {
c, err := redis.Dial("tcp", "127.0.0.1:6379")
if err != nil {
fmt.Println("Connect to redis error", err)
return
}
defer c.Close()
_, err = c.Do("SET", "willen_key", 1, "EX", "5")
if err != nil {
fmt.Println("redis set failed:", err)
}

score, err := redis.String(c.Do("GET", "willen_key"))
if err != nil {
fmt.Println("redis get failed:", err)
} else {
fmt.Printf("Get willen_key: %v \n", score)
}
time.Sleep(5 * time.Second)
fmt.Println("after 5 second")
score, err = redis.String(c.Do("GET", "willen_key"))
if err != nil {
fmt.Println("redis get failed:", err)
} else {
fmt.Printf("Get willen_key: %v \n", score)
}
fmt.Println("#######zset function########")
for i :=1; i<5; i++ {
_, err = c.Do("zadd", "willen_zset", i ,i)
if err != nil {
fmt.Println("redis set failed:", err)
}
}
_, err = c.Do("zadd", "willen_zset", 123, 1)
if err != nil {
fmt.Println("redis set failed:", err)
}

4000
result, err := redis.Values(c.Do("zrevrange", "willen_zset", "0", "-1", "WITHSCORES"))
for _, v := range result {
fmt.Println(string(v.([]byte)))
}
}
wujingcideMacBook-Pro:redigo wujingci$ go run redigo.go
Get willen_key: 1
after 5 second
redis get failed: redigo: nil returned
#######zset function########
1
123
4
4
3
3
2
2


redis是官网例子改的

wujingcideMacBook-Pro:redis wujingci$ cat redis.go
package main
import "github.com/go-redis/redis"
import "fmt"

func main() {
client := redis.NewClient(&redis.Options{
Addr:     "127.0.0.1:6379",
DB:       0,  // use default DB
})
err := client.Set("key", "value", 0).Err()
if err != nil {
panic(err)
}

val, err := client.Get("key").Result()
if err != nil {
panic(err)
}
fmt.Println("key", val)

val2, err := client.Get("key2").Result()
if err == redis.Nil {
fmt.Println("key2 does not exist")
} else if err != nil {
panic(err)
} else {
fmt.Println("key2", val2)
}
// Output: key value
// key2 does not exist
}

wujingcideMacBook-Pro:redis wujingci$ go run redis.go
key value
key2 does not exist


详细文档查询redis godoc
标签: