public static bool ConcurrentUpdate <T>(string gkey, MemcachedConcurrentUpdater <T> updater, out T updatedData) { if (updater == null) { throw new ArgumentNullException("updater"); } var client = GetClientInstance(); updatedData = default(T); int tryTimes = 0; MemcachedClient.CasResult casRst; ulong unique; do { if (tryTimes >= 5) { throw new ApplicationException("已经尝试了5次,都无法访问memcached服务"); } if (tryTimes >= 2) { Thread.Sleep(50); } T originalDate; CacheItem tmp = client.Gets(gkey, out unique) as CacheItem; if (tmp == null || tmp.Data == null) { originalDate = default(T); } else { originalDate = (T)tmp.Data; } bool needUpdate; updatedData = updater(originalDate, out needUpdate); if (needUpdate == false) { return(false); } var itemData = new NeverExpiredCacheItem(gkey, updatedData, null); if (unique == 0) // 说明还不存在,需要新增 { casRst = client.Add(gkey, itemData) ? MemcachedClient.CasResult.Stored : MemcachedClient.CasResult.NotStored; } else { casRst = client.CheckAndSet(gkey, itemData, unique); // 满足条件则更新缓存 } tryTimes++; } while (casRst != MemcachedClient.CasResult.Stored); // 这种写法防止并发冲突 return(true); }
public static bool ConcurrentUpdateFromDistributedCache <T>(string key, MemcachedConcurrentUpdater <T> updater, out T updatedData) { return(MemcachedCacheHelper.ConcurrentUpdate(key, updater, out updatedData)); }