Explorar o código

fix: update cache immediately after cache get

Co-authored-by: chikasaki <1347283135@qq.com>
Co-authored-by: Cruel <157922018@qq.com>
JustSong %!s(int64=2) %!d(string=hai) anos
pai
achega
86c2627c24
Modificáronse 3 ficheiros con 18 adicións e 1 borrados
  1. 5 0
      common/redis.go
  2. 5 1
      controller/relay-text.go
  3. 8 0
      model/cache.go

+ 5 - 0
common/redis.go

@@ -61,3 +61,8 @@ func RedisDel(key string) error {
 	ctx := context.Background()
 	ctx := context.Background()
 	return RDB.Del(ctx, key).Err()
 	return RDB.Del(ctx, key).Err()
 }
 }
+
+func RedisDecrease(key string, value int64) error {
+	ctx := context.Background()
+	return RDB.DecrBy(ctx, key, value).Err()
+}

+ 5 - 1
controller/relay-text.go

@@ -194,7 +194,11 @@ func relayTextHelper(c *gin.Context, relayMode int) *OpenAIErrorWithStatusCode {
 	if err != nil {
 	if err != nil {
 		return errorWrapper(err, "get_user_quota_failed", http.StatusInternalServerError)
 		return errorWrapper(err, "get_user_quota_failed", http.StatusInternalServerError)
 	}
 	}
-	if userQuota > 10*preConsumedQuota {
+	err = model.CacheDecreaseUserQuota(userId, preConsumedQuota)
+	if err != nil {
+		return errorWrapper(err, "decrease_user_quota_failed", http.StatusInternalServerError)
+	}
+	if userQuota > 100*preConsumedQuota {
 		// in this case, we do not pre-consume quota
 		// in this case, we do not pre-consume quota
 		// because the user has enough quota
 		// because the user has enough quota
 		preConsumedQuota = 0
 		preConsumedQuota = 0

+ 8 - 0
model/cache.go

@@ -95,6 +95,14 @@ func CacheUpdateUserQuota(id int) error {
 	return err
 	return err
 }
 }
 
 
+func CacheDecreaseUserQuota(id int, quota int) error {
+	if !common.RedisEnabled {
+		return nil
+	}
+	err := common.RedisDecrease(fmt.Sprintf("user_quota:%d", id), int64(quota))
+	return err
+}
+
 func CacheIsUserEnabled(userId int) bool {
 func CacheIsUserEnabled(userId int) bool {
 	if !common.RedisEnabled {
 	if !common.RedisEnabled {
 		return IsUserEnabled(userId)
 		return IsUserEnabled(userId)