This commit is contained in:
zhengchiliu
2026-09-15 00:53:04 +08:00
parent 32a0b87e9e
commit 112c5f8e46
42 changed files with 1121 additions and 304 deletions
+14 -3
View File
@@ -117,10 +117,14 @@ func QuotaDailyClosetShareValue(ctx context.Context, userID int64, date int64) (
// ---- 通用每日额度原子限流(带限额) ----
// dailyQuotaConsumeScript 带限额的原子自增:
// KEYS[1]=当日计数 key;ARGV[1]=每日上限;ARGV[2]=消费数量;ARGV[3]=TTL 秒。
//
// KEYS[1]=当日计数 key;ARGV[1]=每日上限;ARGV[2]=消费数量;ARGV[3]=TTL 秒。
//
// 当前计数 + n 超过上限返回 -1;否则 INCRBY 并在首次写入时设置 TTL,返回消费后的当日计数。
var dailyQuotaConsumeScript = redis.NewScript(`
local v = tonumber(redis.call('GET', KEYS[1]) or '0')
local baseline = tonumber(ARGV[4])
if baseline > v then v = baseline; redis.call('SET', KEYS[1], v); redis.call('EXPIRE', KEYS[1], ARGV[3]) end
local limit = tonumber(ARGV[1])
local n = tonumber(ARGV[2])
if v + n > limit then
@@ -149,14 +153,14 @@ return redis.call('DECRBY', KEYS[1], n)
// DailyQuotaConsume 原子消费当日额度。
// 返回 (消费后计数, nil);额度不足返回 (-1, nil);Redis 异常返回 (0, err)。
func DailyQuotaConsume(ctx context.Context, key string, limit int64, n int64) (int64, error) {
func DailyQuotaConsume(ctx context.Context, key string, limit int64, n int64, baseline int64) (int64, error) {
ctx, span := global.Tracer.Start(ctx, "redisdao.DailyQuotaConsume")
defer span.End()
if limit <= 0 || n <= 0 {
return -1, nil
}
val, err := dailyQuotaConsumeScript.Run(ctx, global.RedisEngine, []string{key}, limit, n, int(quotaDailyTTL.Seconds())).Int64()
val, err := dailyQuotaConsumeScript.Run(ctx, global.RedisEngine, []string{key}, limit, n, int(quotaDailyTTL.Seconds()), baseline).Int64()
if err != nil {
span.RecordError(err)
return 0, err
@@ -184,3 +188,10 @@ func DailyQuotaValue(ctx context.Context, key string) (int64, error) {
return quotaDailyValue(ctx, key)
}
// DailyQuotaDelete 删除每日计数缓存;MySQL 是权威账本,后续读取会从数据库恢复。
func DailyQuotaDelete(ctx context.Context, key string) error {
if key == "" || global.RedisEngine == nil {
return nil
}
return global.RedisEngine.Del(ctx, key).Err()
}