Skip to main content

[pkg] go-redis 筆記

基本使用#

建立 client#

// https://ithelp.ithome.com.tw/articles/10249929
func NewClient(ctx context.Context) *redis.Client {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
pong, err := client.Ping(ctx).Result()
if err != nil {
panic(err)
}
fmt.Println(pong)
return client
}
func main() {
ctx := context.Background()
client := NewClient(ctx)
}

使用 client 設值#

// https://ithelp.ithome.com.tw/articles/10249929
func main() {
ctx := context.Background()
client := NewClient(ctx)
if err := client.Set(ctx, "key", "value", 0).Err(); err != nil {
log.Println("client.Set failed", err)
}
}

使用 client 取值#

// https://ithelp.ithome.com.tw/articles/10249929
func main() {
ctx := context.Background()
client := NewClient(ctx)
// 取值
val, err := client.Get(ctx, "key").Result()
if err != nil {
log.Println("client.Get failed", err)
}
// 取值並判斷值是否存在
val2, err := client.Get(ctx, "key2").Result()
if err == redis.Nil {
fmt.Println("val2 does not exist")
} else if err != nil {
fmt.Println("client.Get failed", err)
} else {
fmt.Println("key2", val2)
}
}

參考#

Last updated on