From 8310676a4749c3a251837ccc067c39cc4f1727ae Mon Sep 17 00:00:00 2001 From: redhat <2292650292@qq.com> Date: Mon, 10 Feb 2025 09:36:54 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E8=87=AA=E5=8A=A8=E7=BB=AD?= =?UTF-8?q?=E6=9C=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.go | 2 +- redisLock/redis.go | 36 ++++++++++++++++++++++++++++++++---- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 75ca166..b1722bb 100644 --- a/main.go +++ b/main.go @@ -23,7 +23,7 @@ func main() { e := engine.FirstEngine{ Scheduler: &scheduler.FirstScheduler{}, - WorkCount: 10, + WorkCount: 15, Work: client.CreateRpcWorker(createRpcPoll(*host)), } diff --git a/redisLock/redis.go b/redisLock/redis.go index 092bd90..8e0794a 100644 --- a/redisLock/redis.go +++ b/redisLock/redis.go @@ -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 + } + } + } +}