package main
import (
"context"
"errors"
"fmt"
"github.com/go-redis/redis/v8"
)
// go get github.com/go-redis/redis/v8
var ctx = context.Background()
func main() {
ExampleClient()
}
func ExampleClient() {
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
err := rdb.Set(ctx, "key", "value", 0).Err()
if err != nil {
panic(err)
}
val, err := rdb.Get(ctx, "key").Result()
if err != nil {
panic(err)
}
fmt.Println("key", val)
script := `return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}`
res, err := rdb.Eval(ctx, script, []string{"key1", "key2"}, "ag1", "arg2").Result()
fmt.Printf("Eval T=%T v=%v err=%v\n", res, res, err) // Eval T=[]interface {} v=[key1 key2 ag1 arg2] err=<nil>
script = `if redis.call('get',KEYS[1]) then return 0;else return 1 end`
res, err = rdb.Eval(ctx, script, []string{"key2"}).Result()
fmt.Printf("Eval2 T=%T v=%v err=%v\n", res, res, err) // Eval2 T=int64 v=1 err=<nil>( key2存在返回0,不存在返回1)
script = `local v = redis.call('get',KEYS[1]);if v then redis.call('del',KEYS[1]);return 1;end;return 0;` // 获取 key 的值,如果有值,则删除并返回1;如果key不存在,则返回0;
res, err = rdb.Eval(ctx, script, []string{"key"}).Int64()
fmt.Printf("Eval3 T=%T v=%v err=%v\n", res, res, err) // Eval3 T=int64 v=1 err=<nil>
val, err = rdb.Get(ctx, "key").Result()
if err != nil {
if errors.Is(err, redis.Nil) {
fmt.Println("nil:", err.Error()) // nil: redis: nil
}
}
fmt.Println("key", val)
}