1.缓存辅助方法类的接口代码:

  public interface IThrottleStore
    {
        /// <summary>
        /// 试图获取值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="entry"></param>
        /// <returns></returns>
        bool TryGetValue(string key, out ThrottleEntry entry);

        /// <summary>
        /// 增量请求
        /// </summary>
        /// <param name="key"></param>
        void IncrementRequests(string key);

        /// <summary>
        /// 反转
        /// </summary>
        /// <param name="key"></param>
        void Rollover(string key);

        /// <summary>
        /// 清除
        /// </summary>
        void Clear();
    }

2.缓存辅助方法的实体类代码:

 /// <summary>
    /// 调节实体
    /// </summary>
    public class ThrottleEntry
    {
        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime PeriodStart { get; set; }

        /// <summary>
        /// 请求
        /// </summary>
        public long Requests { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public ThrottleEntry()
        {
            PeriodStart = DateTime.UtcNow;
            Requests = 0;
        }
    }

3.缓存辅助类的实现代码:

 public class InMemoryThrottleStore : IThrottleStore
    {
        /// <summary>
        /// 定义类型字段时,采用线程安全字典
        /// </summary>
        private readonly ConcurrentDictionary<string, ThrottleEntry> _throttleStore = new ConcurrentDictionary<string, ThrottleEntry>();

        public bool TryGetValue(string key, out ThrottleEntry entry)
        {
            return _throttleStore.TryGetValue(key, out entry);
        }

        public void IncrementRequests(string key)
        {
            _throttleStore.AddOrUpdate(key, k => { return new ThrottleEntry() { Requests = 1 }; },
                                       (k, e) => { e.Requests++; return e; });
        }

        public void Rollover(string key)
        {
            ThrottleEntry dummy;
            _throttleStore.TryRemove(key, out dummy);
        }

        public void Clear()
        {
            _throttleStore.Clear();
        }
    }

 

相关文章:

  • 2021-11-23
  • 2021-12-14
  • 2021-05-20
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-14
猜你喜欢
  • 2022-12-23
  • 2021-09-25
  • 2022-12-23
  • 2021-07-22
  • 2022-01-09
  • 2021-12-18
  • 2022-12-23
相关资源
相似解决方案