码迷,mamicode.com
首页 > Web开发 > 详细

.net简单的缓存分片

时间:2019-04-15 15:58:35      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:count   arp   csharp   字典实现   ati   .net   return   highlight   pre   

实现一个内存里面放入三个字典实现字典分片

  static CacheCutting()
        {
            _DictionaryList = new List<Dictionary<string, object>>();
            _ObjectList = new List<object>();
            _DictionaryList.Add(_KeyValues1);
            _DictionaryList.Add(_KeyValues2);
            _DictionaryList.Add(_KeyValues3);
            //加线程锁
            for (int i = 0; i < _DictionaryList.Count; i++)
            {
                _ObjectList.Add(new object());
            }
        }
        private static Dictionary<string, object> _KeyValues1 = new Dictionary<string, object>();
        private static Dictionary<string, object> _KeyValues2 = new Dictionary<string, object>();
        private static Dictionary<string, object> _KeyValues3 = new Dictionary<string, object>();

        private static List<Dictionary<string, object>> _DictionaryList;
        private static List<object> _ObjectList;
        public static void SetValue(string key, object value)
        {

            int hashKey = key.GetHashCode();
            int index = GetInt(key);
            lock (_ObjectList[index])
                _DictionaryList[index].Add(key, value);
        }
        public static object GetValue(string key)
        {
            object result = null;
            int hashKey = key.GetHashCode();
            int index = GetInt(key);
            lock (_ObjectList[index])
            {
                if (_DictionaryList[index].ContainsKey(key))
                    result = _DictionaryList[index][key];
            }
            return result;
        }
        private static int GetInt(string key)
        {
            int hashKey = key.GetHashCode();
            int hashList = hashKey % _DictionaryList.Count;
            return Math.Abs(hashList);
        }

  

.net简单的缓存分片

标签:count   arp   csharp   字典实现   ati   .net   return   highlight   pre   

原文地址:https://www.cnblogs.com/zxp6/p/10710821.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!