From 0710f8cd66cfb2b13ad25b0fdf4212d74e5abf73 Mon Sep 17 00:00:00 2001 From: JustSong Date: Wed, 13 Mar 2024 19:26:24 +0800 Subject: [PATCH] fix: when cached quota is too low, force refresh it --- model/cache.go | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/model/cache.go b/model/cache.go index 3c3575b8..3a9f8023 100644 --- a/model/cache.go +++ b/model/cache.go @@ -70,23 +70,30 @@ func CacheGetUserGroup(id int) (group string, err error) { return group, err } +func fetchAndUpdateUserQuota(id int) (quota int, err error) { + quota, err = GetUserQuota(id) + if err != nil { + return 0, err + } + err = common.RedisSet(fmt.Sprintf("user_quota:%d", id), fmt.Sprintf("%d", quota), time.Duration(UserId2QuotaCacheSeconds)*time.Second) + if err != nil { + logger.SysError("Redis set user quota error: " + err.Error()) + } + return +} + func CacheGetUserQuota(id int) (quota int, err error) { if !common.RedisEnabled { return GetUserQuota(id) } quotaString, err := common.RedisGet(fmt.Sprintf("user_quota:%d", id)) if err != nil { - quota, err = GetUserQuota(id) - if err != nil { - return 0, err - } - err = common.RedisSet(fmt.Sprintf("user_quota:%d", id), fmt.Sprintf("%d", quota), time.Duration(UserId2QuotaCacheSeconds)*time.Second) - if err != nil { - logger.SysError("Redis set user quota error: " + err.Error()) - } - return quota, err + return fetchAndUpdateUserQuota(id) } quota, err = strconv.Atoi(quotaString) + if quota <= config.PreConsumedQuota { // when user's quota is less than pre-consumed quota, we need to fetch from db + return fetchAndUpdateUserQuota(id) + } return quota, err }