Skip to content

Commit

Permalink
增加限流埋点,方便分析问题
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed May 23, 2024
1 parent 9c58a15 commit 7e7e5c9
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions NewLife.CubeNC/Services/AccessService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,16 +117,18 @@ private Boolean ValidLimit(AccessRule rule, String url, String userAgent, String
var sec = (Int32)(now - now.Date).TotalSeconds;
var time = sec / rule.LimitCycle;

// 限流缓存键
var cacheKey = $"access:{rule.Id}:{key}:{time}";
if (session != null) session["_access_limit"] = cacheKey;

var count = _cacheProvider.Cache.Increment(cacheKey, 1);
if (count > rule.LimitTimes) return false;

if (count <= 2)
{
// 递增并设置过期时间
var hits = _cacheProvider.Cache.Increment(cacheKey, 1);
if (hits <= 2)
_cacheProvider.Cache.SetExpire(cacheKey, TimeSpan.FromSeconds(rule.LimitCycle));
}

DefaultSpan.Current?.AppendTag($"cacheKey={cacheKey} startTime={TimeSpan.FromSeconds(time * rule.LimitCycle)} hits={hits}");

if (hits > rule.LimitTimes) return false;

return true;
}
Expand Down

0 comments on commit 7e7e5c9

Please sign in to comment.