C# RedisRateLimiter

2018/12/25 08:56
阅读数 0
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;
    }
}
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部