增加自动续期

This commit is contained in:
redhat 2025-02-10 09:36:54 +08:00
parent 868d533c8f
commit 8310676a47
2 changed files with 33 additions and 5 deletions

View File

@ -23,7 +23,7 @@ func main() {
e := engine.FirstEngine{
Scheduler: &scheduler.FirstScheduler{},
WorkCount: 10,
WorkCount: 15,
Work: client.CreateRpcWorker(createRpcPoll(*host)),
}

View File

@ -15,13 +15,14 @@ type redisCommInfo struct {
}
type RedisLock struct {
client *redis.Client
ctx context.Context
kvt redisCommInfo
client *redis.Client
ctx context.Context
lockKeepAliveCh chan struct{}
kvt redisCommInfo
}
func CreateRedisLock(c *redis.Client, ctx context.Context, k, v string, ttl int) *RedisLock {
return &RedisLock{c, ctx, redisCommInfo{k, v, ttl}}
return &RedisLock{c, ctx, make(chan struct{}, 1), redisCommInfo{k, v, ttl}}
}
func (r *RedisLock) Lock() {
@ -41,6 +42,13 @@ func (r *RedisLock) Lock() {
time.Sleep(time.Millisecond * 20)
}
select {
case r.lockKeepAliveCh <- struct{}{}:
go r.autoReNewExpire()
default:
}
log.Printf("lock ok: %s,%s,%d\n", r.kvt.key, r.kvt.value, r.kvt.ttl)
}
@ -59,3 +67,23 @@ func (r *RedisLock) Unlock() {
log.Printf("unlock ok: %s,%s,%d\n", r.kvt.key, r.kvt.value, r.kvt.ttl)
}
func (r *RedisLock) autoReNewExpire() {
defer func() {
<-r.lockKeepAliveCh
}()
tc := time.NewTicker(time.Duration(r.kvt.ttl) * time.Second / 3)
defer tc.Stop()
for {
select {
case <-tc.C:
script := `if redis.call('hexists',KEYS[1],ARGV[1]) == 1 then return redis.call('expire',KEYS[1],ARGV[2])
else return 0 end`
if r.client.Eval(r.ctx, script, []string{r.kvt.key}, r.kvt.value).Val().(int64) == 0 {
return
}
}
}
}