Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

添加go对于Redis的用法示例 #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions ex_05_redis/main.go
Original file line number Diff line number Diff line change
@@ -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")
}
4 changes: 4 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
)