go_redis

Last updated on 3 months ago

下载

go get github.com/go-redis/redis/v8
我是使用docker拉取redis镜像然后挂载本地磁盘(csdn一搜就有)

连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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不存在

}


go_redis
https://blog.yblue.top/2023/10/25/go-redis/
Posted on
October 25, 2023
Licensed under