From 5482fff62dddcd4e55306ff20223625beb7bf34c Mon Sep 17 00:00:00 2001 From: "1808837298@qq.com" <1808837298@qq.com> Date: Tue, 20 Feb 2024 00:23:31 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8Dredis=E7=BC=93?= =?UTF-8?q?=E5=AD=98=E7=94=A8=E6=88=B7=E9=A2=9D=E5=BA=A6=E4=B8=8D=E8=BF=87?= =?UTF-8?q?=E6=9C=9F=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/redis.go | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/common/redis.go b/common/redis.go index 54a7cb30..2e3e56d6 100644 --- a/common/redis.go +++ b/common/redis.go @@ -73,6 +73,35 @@ func RedisDel(key string) error { } func RedisDecrease(key string, value int64) error { - ctx := context.Background() - return RDB.DecrBy(ctx, key, value).Err() + + // 检查键的剩余生存时间 + ttlCmd := RDB.TTL(context.Background(), key) + ttl, err := ttlCmd.Result() + if err != nil { + // 失败则尝试直接减少 + return RDB.DecrBy(context.Background(), key, value).Err() + } + + // 如果剩余生存时间大于0,则进行减少操作 + if ttl > 0 { + ctx := context.Background() + // 开始一个Redis事务 + txn := RDB.TxPipeline() + + // 减少余额 + decrCmd := txn.DecrBy(ctx, key, value) + if err := decrCmd.Err(); err != nil { + return err // 如果减少失败,则直接返回错误 + } + + // 重新设置过期时间,使用原来的过期时间 + txn.Expire(ctx, key, ttl) + + // 执行事务 + _, err = txn.Exec(ctx) + return err + } else { + _ = RedisDel(key) + } + return nil }