redis-tools is a collection of redis tools, including distributed lock
, cas
, casEx
, cad
.
Fisrt, create a demo and import the redis-tools and redis client :
> go mod init demo
> go get github.com/zehuamama/redis-tools
> go get github.com/go-redis/redis/v8
The trylock
case :
package main
import (
"context"
"log"
"github.com/go-redis/redis/v8"
tools "github.com/zehuamama/redis-tools"
)
func main() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
disLock, err := tools.NewRedisLock(client, "lock resource")
if err != nil {
log.Fatal(err)
}
succ, err := disLock.TryLock(context.Background())
if err != nil {
log.Println(err)
return
}
if succ {
defer disLock.Unlock(context.Background())
}
}
and spinlock
case :
succ, err := disLock.SpinLock(context.Background(), 5) // retry 5 times
if err != nil {
log.Println(err)
return
}
if succ {
defer disLock.Unlock(context.Background())
}
compare and swap
case :
func main() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
succ, err := tools.NewTools(client).Cas(context.Background(), "cas_key", "old value", "new value")
if err != nil {
log.Println(err)
return
}
...
}
and compare and delete
case :
succ, err := tools.NewTools(client).Cad(context.Background(), "cas_key", "old value")
if err != nil {
log.Println(err)
return
}
If you are intersted in contributing to redis-tools, please see here: CONTRIBUTING
redis-tools is licensed under the term of the BSD 2-Clause License