From 28710cf6a7c044519c62e2d7dbbf6ef34c115e5e Mon Sep 17 00:00:00 2001 From: songyang Date: Fri, 20 Sep 2024 16:53:40 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0go=E5=AF=B9=E4=BA=8ERedis?= =?UTF-8?q?=E7=9A=84=E7=94=A8=E6=B3=95=E7=A4=BA=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ex_05_redis/main.go | 64 +++++++++++++++++++++++++++++++++++++++++++++ go.mod | 4 +++ 2 files changed, 68 insertions(+) create mode 100644 ex_05_redis/main.go diff --git a/ex_05_redis/main.go b/ex_05_redis/main.go new file mode 100644 index 0000000..f051da0 --- /dev/null +++ b/ex_05_redis/main.go @@ -0,0 +1,64 @@ +package main + +import ( + "context" + "fmt" + "github.com/redis/go-redis/v9" + "time" +) + +func main() { + rdb := redis.NewClient(&redis.Options{ + Addr: "localhost:6379", + Password: "", // 没有密码,默认值 + DB: 0, // 默认DB 0 + }) + ctx := context.Background() + // Redis kv结构 + rdb.Set(ctx, "redis:string", "bar", time.Second*10) + val, _ := rdb.Get(ctx, "redis:string").Result() + fmt.Println("redis kv 获取的值是:", val) + rdb.Del(ctx, "redis:string") + + // Redis list结构 + rdb.LPush(ctx, "redis:list", "bar", "foo") + listResult, _err := rdb.LRange(ctx, "redis:list", 0, -1).Result() + if _err != nil { + panic(_err) + } + for index, item := range listResult { + fmt.Println(fmt.Sprintf("redis list 获取的值是: %s,index: %d ", item, index)) + } + rdb.Del(ctx, "redis:list") + + // Redis hash结构 + rdb.HSet(ctx, "redis:hash", "foo", "bar") + hashResult, _err := rdb.HGetAll(ctx, "redis:hash").Result() + if _err != nil { + panic(_err) + } + for key, value := range hashResult { + fmt.Println(fmt.Sprintf("redis hash 获取的值是: key: %s, value: %s", key, value)) + } + rdb.Del(ctx, "redis:hash") + + // Redis set结构 + rdb.SAdd(ctx, "redis:set", "foo", "bar") + setResult, _err := rdb.SMembers(ctx, "redis:set").Result() + if _err != nil { + panic(_err) + } + for _, item := range setResult { + fmt.Println(fmt.Sprintf("redis set 获取的值是: %s", item)) + } + // Redis set结构删除 + rdb.SRem(ctx, "redis:set", "foo") + setResult, _err = rdb.SMembers(ctx, "redis:set").Result() + if _err != nil { + panic(_err) + } + for _, item := range setResult { + fmt.Println(fmt.Sprintf("redis set 删除后获取的值是: %s", item)) + } + rdb.Del(ctx, "redis:set") +} diff --git a/go.mod b/go.mod index a9d0949..bbd67e2 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,11 @@ go 1.18 require github.com/tidwall/gjson v1.14.4 +require github.com/redis/go-redis/v9 v9.6.1 + require ( + github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/tidwall/match v1.1.1 // indirect github.com/tidwall/pretty v1.2.1 // indirect )