AsNum.Throttle
2020-05-08 本文已影响0人
gruan
Action throttle in a period.
如果你想限制某个方法在1秒钟内只能执行10次, 可以按如下方式限定:
InProcess 进程内使用
Throttle TS = new Throttle("ThrottleName", TimeSpan.FromSeconds(1), 10);
...
this.TS.Execute(()=> ...);
...
Cross Process 跨进程
跨进程的 Block 用 Semaphore
实现, 但是同时也需要分布式缓存
用于计数
this.Block = new CrossProcessBlock();
var conn = RedisExchangeManager.GetConnection(RedisNames.Mix);
this.Counter = new RedisCounter(conn);
this.TS = new Throttle("ThrottleName", TimeSpan.FromSeconds(1), 10, this.Block, this.Counter);
Cross Server 跨服务器
跨服务器的 Block 是通过 Redis 来实现的
原本是想用
BLPOP
来实现 BLOCK 的, 但是StackExchange.Redis
中没有实现该方法.
所以, 这里用订阅发布
加上AutoResetEvent
来模拟了 BLOCK 操作.
原思路:
RedisBLPOP
/BRPOP
如果队列为空, 则阻塞连接, 直到队列中的对象可以出队时在返回。
和要求的入队阻塞刚好向反。
入队一次, 从 REDIS 队列中删除(BLPOP / BRPOP )一个,则直到 REDIS 队列为空, 就不能在入队了。
出队一次, 向 REDIS 队列中添加一个。
this.Block = new RedisBlock(conn);
Git
https://github.com/gruan01/Throttle/tree/master
NUGET
性能计数器 (总数计数
上有些BUG, 故这个包只做开发使用, 不用作生产):
AsNum.Throttle.Statistic