```go package main import ( "fmt" "github.com/go-redis/redis" "time" ) // 定义一个全局的redis客户端 var redisClient *redis.ClusterClient // 初始化redis客户端 func initRedis() (err error) { redisClient = redis.NewClusterClient(&redis.ClusterOptions{ Addrs: []string{"127.0.0.1:7000", "127.0.0.1:7001", "127.0.0.1:7002", "127.0.0.1:7003", "127.0.0.1:7004", "127.0.0.1:7005"}, Password: "", PoolSize: 10, }) _, err = redisClient.Ping().Result() return } // 加锁 func Lock(key string, value string, timeout int) (lockSucc bool, err error) { // 加锁 // SET key value NX PX timeout // key: 锁的key // value: 锁的值 // NX: 不存在时才设置 // PX: 过期时间 // timeout: 过期时间,单位毫秒 // 返回值: // OK: 加锁成功 // nil: 加锁失败 result, err := redisClient.SetNX(key, value, time.Duration(timeout)*time.Millisecond).Result() if err != nil { return } lockSucc = result return } // 解锁 func UnLock(key string, value string) (unLockSucc bool, err error) { // 解锁 // 判断key对应的value是否是自己的,如果是自己的,则删除key script := ` if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end ` // 执行lua脚本 result, err := redisClient.Eval(script, []string{key}, value).Result() if err != nil { return } // 返回值: // 1: 解锁成功 // 0: 解锁失败 unLockSucc = result.(int64) == 1 return } func main() { err := initRedis() if err != nil { fmt.Printf("init redis failed, err:%vn", err) return } fmt.Println("init redis succ") key := "lock_key" value := "lock_value" timeout := 10000 // 加锁 lockSucc, err := Lock(key, value, timeout) if err != nil { fmt.Printf("lock failed, err:%vn", err) return } if !lockSucc { fmt.Printf("lock failed, key:%s already lockedn", key) return } fmt.Printf("lock succ, key:%sn", key) // 解锁 unLockSucc, err := UnLock(key, value) if err != nil { fmt.Printf("unlock failed, err:%vn", err) return } if !unLockSucc { fmt.Printf("unlock failed, key:%s already unlockedn", key) return } fmt.Printf("unlock succ, key:%sn", key) } ```