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 = COUN...
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;
}
}
沃梦达教程
本文标题为:C# RedisRateLimiter
基础教程推荐
猜你喜欢
- C#图表算法之最短路径 2023-06-05
- C#中LINQ to DataSet操作及DataTable与LINQ相互转换 2023-06-08
- 解析C# 程序结构 2023-04-22
- C#中的9个“黑魔法” 2023-02-09
- WindowsForm实现警告消息框的实例代码 2023-03-09
- C#使用ScrapySharp快速从网页采集数据 2023-06-21
- 温故知新,.Net Core遇见JWT(JSON Web Token)授权机制方案 2023-09-28
- c# – 在Windows Mobile应用程序中存储应用程序设置的首选方法是什么? 2023-09-18
- C# 获取 PC 序列号的方法示例 2022-12-30
- C#并行编程之PLINQ(并行LINQ) 2023-06-05