public class RedisRateLimiter
{
private static Logger LOG = LogManager.GetLogger("redis-limiter");
private static readonly string TIME_KEY = "TIME_KEY";
private static readonly string COUNTER_KEY = "COUNTER_KEY";
public int MaxLimitNum { get; set; }
public RedisRateLimiter(int maxLimitNum)
{
this.MaxLimitNum = maxLimitNum;
}
public bool CheckLimit()
{
using (var redisClient = RedisUtil.GetClient())
{
if (!redisClient.ContainsKey(TIME_KEY))
{
LOG.Debug("Key Exp");
redisClient.Set<int>(TIME_KEY, 0, TimeSpan.FromSeconds(1));
redisClient.Set<long>(COUNTER_KEY, 0, TimeSpan.FromSeconds(1));
}
if (redisClient.ContainsKey(TIME_KEY))
{
var current = redisClient.IncrementValue(COUNTER_KEY);
if (current > MaxLimitNum)
{
LOG.Error("限流成功,当前值: {0}, 限制最大值:{1}", current, MaxLimitNum);
return false;
}
}
}
return true;
}
}