.net简单的缓存分片

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

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

  

猜你喜欢

转载自www.cnblogs.com/zxp6/p/10710821.html