下载
我是使用docker拉取redis镜像然后挂载本地磁盘(csdn一搜就有)
# 连接
```go
package main
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
"time"
)
func main() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
//键名是name,键值是123,10s后过期(过期是键跟键值全删除,不是mysql那种软删除)
err := rdb.Set(ctx, "name", "123", 10*time.Second).Err()
if err != nil {
panic(err)
}
//通过键名访问键值
val, err := rdb.Get(ctx, "name").Result()
if err != nil {
panic(err)
}
val2, err := rdb.Get(ctx, "key2").Result()
if err == redis.Nil {
fmt.Println("key2 does not exist")
} else if err != nil {
panic(err)
} else {
fmt.Println("key2", val2)
}
fmt.Println("name", val)
/*
C:GoLand\___go_build_RedisTest_go.exe
key2 does not exist
name 123
*/
//panic的会被defer,最后执行,所以先打印key2不存在
}
Category: go |
Tags: go,redis |
Created: 2024-11-29 14:53:20