go-redis
最后更新于:2022-04-02 02:37:57
[TOC]
> [github](https://github.com/go-redis/redis/)
## 安装
go 必须支持mod
```
go get github.com/go-redis/redis/v7
```
## 实例
### hello word
```
func ExampleNewClient() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
pong, err := client.Ping().Result()
fmt.Println(pong, err)
// Output: PONG
}
func ExampleClient() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
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
}
```
### 管道
管道的数据不可中途获取
```
func ExampleClient_TxPipeline() {
pipe := rdb.TxPipeline()
incr := pipe.Incr("tx_pipeline_counter")
pipe.Expire("tx_pipeline_counter", time.Hour)
//pipe.Get()
//...
_, err := pipe.Exec()
fmt.Println(incr.Val(), err)
//数据得最后获取
}
```
';