/// <summary> /// /// </summary> /// <param name="period">周期</param> /// <param name="maxCountPerPeriod">周期内最大允许执行次数</param> /// <param name="block"></param> /// <param name="counter"></param> /// <param name="lockTimeout">避免因为客户端失去连接而引起的死锁</param> /// <param name="concurrentCount">并发数</param> /// <param name="throttleName">应该是一个唯一的字符串, 这个参数做为 Redis 的 key 的一部份, 因此要符合 redis key 的规则</param> public Throttle(string throttleName, TimeSpan period, int maxCountPerPeriod, BaseBlock block, BaseCounter counter, TimeSpan?lockTimeout = null, int?concurrentCount = null ) { if (string.IsNullOrWhiteSpace(throttleName)) { throw new ArgumentException($"{nameof(throttleName)} 必填"); } if (period <= TimeSpan.Zero) { throw new ArgumentException($"{nameof(period)} 无效"); } if (maxCountPerPeriod <= 0) { throw new ArgumentException($"{nameof(maxCountPerPeriod)} 无效"); } if (concurrentCount.HasValue && concurrentCount <= 0) { throw new ArgumentException($"{nameof(concurrentCount)} 无效"); } if (concurrentCount.HasValue) { this.semaphoreSlim = new SemaphoreSlim(concurrentCount.Value, concurrentCount.Value); } this.ThrottleName = throttleName; this.ThrottleID = Guid.NewGuid().ToString(); this.MaxCountPerPeriod = maxCountPerPeriod; this.Period = period; this.block = block ?? throw new ArgumentNullException(nameof(block)); this.block.Setup(throttleName, this.ThrottleID, maxCountPerPeriod, period, lockTimeout); this.counter = counter ?? throw new ArgumentNullException(nameof(counter)); this.counter.SetUp(throttleName, this.ThrottleID, maxCountPerPeriod, period, lockTimeout); this.counter.OnReset += Counter_OnReset; }
/// <summary> /// /// </summary> /// <param name="throttleName">应该是一个唯一的字符串, 这个参数做为 Redis 的 key 的一部份, 因此要符合 redis key 的规则</param> /// <param name="period"></param> /// <param name="maxCountPerPeriod"></param> /// <param name="counter"></param> /// <param name="blockTimeout"></param> /// <param name="concurrentCount"></param> public Throttle(string throttleName, TimeSpan period, int maxCountPerPeriod, BaseCounter counter, TimeSpan?blockTimeout = null, int?concurrentCount = null ) : this(throttleName, period, maxCountPerPeriod, new DefaultBlock(), counter, blockTimeout, concurrentCount ) { }