从业务的角度考虑使用分布式锁

  在消费者一端采用异步处理数据,但是从队列里面拉取出来的数据有一些会是重复的,所以在异步处理中,需要有一个节点来控制重复插入数据的问题,想到同步序列处理,必然是使用到锁的概念。一般情况下使用Lock来锁住一个代码块,使达到并行到串行的效果,但是去重复的效果达不到,其实重复的数据在数据库insert的时候有校验,但是在高并发的的情况下也是会有失效的情况,因为业务逻辑链条相对较长,所以这里采用的redis实现一个锁。

  

        public List<T> GetCacheList(string dataKey, string signKey,
            List<T> idList,string message)
        {
            if (idList == null || idList.Count < 1)
            {
                return new List<T>();
            }

            StackExchangeRedisBase redis = new StackExchangeRedisBase(_dbNum);
            string ountSignKey = redis.Get(signKey);
            if (string.IsNullOrEmpty(ountSignKey))
            {
                ountSignKey = Guid.NewGuid().ToString();
                redis.Set(signKey, ountSignKey, 10);
            }

            var listRes = GetCurrentList(dataKey, signKey, idList, message, ref ountSignKey);
            var currentSign = redis.Get(signKey);
            if (ountSignKey.Equals(currentSign))
                return listRes;
            else
                return GetCacheList(dataKey, signKey, idList,message);
        }

  
        private List<T> GetCurrentList(string dataKey, string signKey, List<T> idList, string message, ref string outSignKey)
        {
            if (idList == null || idList.Count < 1)
            {
                return new List<T>();
            }

            StackExchangeRedisBase redis = new StackExchangeRedisBase(_dbNum);
            var listRes = new List<T>(idList);
            var dataList = redis.GetList<string>(dataKey);
            var isChange = false;
            if (dataList == null)
                dataList = new List<string>();
            idList.ForEach(t =>
            {
                string tString = JsonConvert.SerializeObject(t).ToString();
                if (dataList.Count > 0 && dataList.Contains(tString.ToString().ToUpper()))
                {
                    listRes.Remove(t);
                }
                 
                else
                {
                    isChange = true;
                    dataList.Add(tString.ToString().ToUpper());
                }
            });

            if (isChange)
            {
                redis.SetList<string>(dataKey, dataList, 10);
                outSignKey = Guid.NewGuid().ToString();
                redis.Set(signKey, outSignKey, 10);
            }
            return listRes;
        }

 

  

posted @ 2017-11-13 10:21  小杨ABC  阅读(182)  评论(0编辑  收藏  举报