Redislock续期
package main
import (
"context"
"fmt"
redis2 "github.com/redis/go-redis/v9"
"testing"
"time"
)
func TestRedisLock(t *testing.T) {
redis := redis2.NewClient(&redis2.Options{
Addr: "xxx:6379",
PoolSize: 10,
PoolTimeout: 5 * time.Second,
})
redisLocker := NewRedisLocker(redis)
redisLocker.Lock("12345")
defer redisLocker.unlock("12345")
}
func NewRedisLocker(redis *redis2.Client) *RedisLocker {
return &RedisLocker{
redis: redis,
}
}
func (l *RedisLocker) Lock(key string) {
rdb := redis2.NewClient(&redis2.Options{
Addr: "xxx:6379",
PoolSize: 10,
PoolTimeout: 5 * time.Second,
})
for {
res, err := rdb.SetNX(context.Background(), key, "1", 10*time.Second).Result()
if err != nil || !res {
fmt.Println(err)
continue
}
break
}
l.done = make(chan struct{})
go func() {
for {
select {
case <-l.done:
return
default:
_, err := rdb.Expire(context.Background(), key, 10*time.Second).Result()
if err != nil {
fmt.Println(err)
}
<-time.After(5 * time.Second)
}
}
}()
}
func (l *RedisLocker) unlock(key string) {
close(l.done)
l.redis.Del(context.Background(), key)
}