C#缓存操作

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();
        }
    }

 

posted @ 2016-10-09 14:56  彭_泽  阅读(776)  评论(0编辑  收藏  举报