private void AddCacheKey(string region, CacheTypeEnum cacheType, string cacheKey) { _typeCacheKeys.AddOrUpdate(region, (reg) => { var newKeyDic = new ConcurrentDictionary <string, byte>(); newKeyDic.GetOrAdd(cacheKey, new byte()); var newTypeDic = new ConcurrentDictionary <CacheTypeEnum, ConcurrentDictionary <string, byte> >(); newTypeDic.GetOrAdd(cacheType, newKeyDic); return(newTypeDic); }, (reg, oldTypeDic) => { oldTypeDic.AddOrUpdate(cacheType, (type) => { var newKeyDic = new ConcurrentDictionary <string, byte>(); newKeyDic.GetOrAdd(cacheKey, new byte()); return(newKeyDic); }, (type, oldKeyDic) => { oldKeyDic.GetOrAdd(cacheKey, new byte()); return(oldKeyDic); }); return(oldTypeDic); }); }
private static bool createCacheInstance(CacheTypeEnum cacheTypeEnum, bool isChangeCacheType = false) { if (_cache != null && !isChangeCacheType) { return(true); } try { lock (locked) { if (cacheTypeEnum.Equals(obj: CacheTypeEnum.Redis)) { _cache = new RedisCacheStrategy(); } if (cacheTypeEnum.Equals(CacheTypeEnum.Memory)) { _cache = new MemoryCacheStrategy(); } } } catch (Exception e) { Console.WriteLine(e.Message); return(false); } return(true); }
/// <summary> /// Get the CacheProvider. /// </summary> /// <param name="cacheType">Type of the cache.</param> /// <returns>ICacheProvider.</returns> public ICacheProvider GetCacheProvider(CacheTypeEnum cacheType) { if (cacheType.EqualNull()) { return(new NullCacheProvider()); } ICacheProvider cacheProvider; switch (cacheType) { case CacheTypeEnum.None: cacheProvider = new NullCacheProvider(); break; case CacheTypeEnum.Memory: cacheProvider = new MemoryCacheProvider(this.ServiceProvider.GetService <IMemoryCache>()); break; case CacheTypeEnum.Redis: cacheProvider = new RedisCacheProvider(this.ServiceProvider.GetService <IDistributedCache>(), TimeSpan.FromHours(1)); break; default: cacheProvider = new NullCacheProvider(); break; } return(cacheProvider); }
private static CacheTypeEnum GetCacheTypeFromConfig() { CacheTypeEnum cacheTypeEnum = CacheTypeEnum.Couchbase; if (!string.IsNullOrWhiteSpace(AppContext.CacheType)) { string str = AppContext.CacheType.ToLower().Trim(); if (str != null) { if (str == "local") { cacheTypeEnum = CacheTypeEnum.Local; } else if (str == "redis") { cacheTypeEnum = CacheTypeEnum.Redis; } else { cacheTypeEnum = CacheTypeEnum.Couchbase; } } } return(cacheTypeEnum); }
public void Add(string region, CacheTypeEnum cacheType, string key, object data, CacheItemPolicy policy) { policy.RemovedCallback += new CacheEntryRemovedCallback((CacheEntryRemovedArguments args) => { _evictCount++; RemoveCacheKey(args.CacheItem.Key); if (_evictCount > _evictCountGC) { lock (_typeCacheLock) { if (_evictCount > _evictCountGC) { _evictCount = 0; GC.Collect(); GC.WaitForPendingFinalizers(); _logger.InfoFormat("GC.Collect is called. [Total Cache Count]={0}, [Total Reg Keys]={1}", _cache.GetCount(), GetAllCount()); } } } }); string cacheKey = BuildCacheKey(region, cacheType, key); if (_cache.Add(cacheKey, data, policy)) { AddCacheKey(region, cacheType, cacheKey); } }
public static ICache Create(CacheTypeEnum cacheType) { ICache instance; switch (cacheType) { case CacheTypeEnum.Local: { instance = LocalCache.Instance; break; } case CacheTypeEnum.Couchbase: { instance = CouchbaseCache.Instance; break; } case CacheTypeEnum.Redis: { instance = RedisCache.Instance; break; } default: { instance = CouchbaseCache.Instance; break; } } return(instance); }
public void Add(string region, CacheTypeEnum cacheType, string key, object data, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority) { CacheItemPolicy policy = new CacheItemPolicy(); policy.AbsoluteExpiration = absoluteExpiration; policy.SlidingExpiration = slidingExpiration; policy.Priority = priority; Add(region, cacheType, key, data, policy); }
private static string BuildCacheKey(string region, CacheTypeEnum cacheType, string key) { if (region == _GLOBAL) { return(string.Format("{0}^{1}", (int)cacheType, key)); } else { return(string.Format("{0}^{1}^{2}", region, (int)cacheType, key)); } }
public ICache ChangeCacheType(CacheTypeEnum cacheTypeEnum) { Console.WriteLine($"Try to switch cache stratety to {cacheTypeEnum.ToString()}"); var suc = createCacheInstance(cacheTypeEnum, true); if (suc) { return(_cache); } return(null); }
public ICache GetCacheInstance(CacheTypeEnum cacheTypeEnum = CacheTypeEnum.Memory) { var suc = createCacheInstance(cacheTypeEnum); if (suc) { return(_cache); } return(null); }
/// <summary> /// 选择为redis缓存时,请指定操作哪个数据库 /// </summary> /// <param name="cacheType"></param> /// <param name="dbNum"></param> public CacheContext(CacheTypeEnum cacheType, int dbNum = -1) { if (cacheType == CacheTypeEnum.LocalCache) { this.strategy = new LocalCacheStrategy(); } else { this.strategy = new RedisStrategy(dbNum); } }
/// <summary> /// Instantiate the configured cache provider /// </summary> /// <returns>Cache instance created</returns> private static ICache GetCacheInstance() { string cache = ConfigurationManager.AppSettings[CacheConstants.MODE] as string; CacheTypeEnum cacheType = CacheTypeEnum.InProcess; Enum.TryParse <CacheTypeEnum>(cache, true, out cacheType); switch (cacheType) { case CacheTypeEnum.InProcess: return(new InMemoryCache()); //case CacheTypeEnum.Distributed: return new RedisCache(); default: return(new InMemoryCache()); } }
public override T Get <T>(string key, long CachingSecond, Func <T> data, CacheTypeEnum type, CacheItemRemovedCallback removedCallback) { if (_cache != null) { var result = _cache.Get(key); if (result == null) { if (data != null) { if (type == CacheTypeEnum.Activity) { if (removedCallback != null) { _cache.Add(key, data, null, DateTime.Now.AddSeconds(CachingSecond), new TimeSpan(CachingSecond * 10), System.Web.Caching.CacheItemPriority.Default, removedCallback); } else { _cache.Add(key, data, null, DateTime.Now.AddSeconds(CachingSecond), new TimeSpan(CachingSecond * 10), System.Web.Caching.CacheItemPriority.Default, null); } } else if (type == CacheTypeEnum.OnTime) { if (removedCallback != null) { _cache.Add(key, data, null, DateTime.Now.AddSeconds(CachingSecond), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, removedCallback); } else { _cache.Add(key, data, null, DateTime.Now.AddSeconds(CachingSecond), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null); } } return((T)_cache.Get(key)); } else { return(default(T)); } } else { if (type == CacheTypeEnum.Once) { _cache.Remove(key); } } } throw new PlatformNotSupportedException("System.Web.HttpRuntime.Cache can be used in this environment! try another way pls."); }
public void Remove(string region, CacheTypeEnum cacheType) { ConcurrentDictionary <CacheTypeEnum, ConcurrentDictionary <string, byte> > typeKeys; if (_typeCacheKeys.TryGetValue(region, out typeKeys)) { ConcurrentDictionary <string, byte> keys; if (typeKeys.TryGetValue(cacheType, out keys)) { foreach (KeyValuePair <string, byte> keyPair in keys) { _cache.Remove(keyPair.Key); } } } }
/// <summary> /// 获取缓存泛型版本 /// </summary> /// <typeparam name="T">缓存对象类型</typeparam> /// <param name="key">缓存键</param> /// <param name="cacheType">缓存类型(默认是Memcached)</param> /// <returns>缓存对象(实际类型)</returns> public static Dictionary <string, T> Get <T>(IEnumerable <string> keys, CacheTypeEnum cacheType = CacheTypeEnum.Default) where T : class { if (keys == null) { return(new Dictionary <string, T>()); } ; if (Refresh() || IsNoCache()) { return(new Dictionary <string, T>()); } switch (cacheType) { case CacheTypeEnum.Memcached: case CacheTypeEnum.Default: default: { var data = Memcached.GetCache(keys); if (data != null) { Dictionary <string, T> dic = new Dictionary <string, T>(); foreach (var item in data) { T t = item.Value as T; dic.Add(item.Key, t); } return(dic); } else { return(new Dictionary <string, T>()); } } case CacheTypeEnum.HttpRuntime: { Dictionary <string, T> dic = new Dictionary <string, T>(); foreach (var key in keys) { var httpRuntimeData = RuntimeCache.GetCache(key); var t = httpRuntimeData != null ? httpRuntimeData as T : null; dic.Add(key, t); } return(dic); } } }
/// <summary> /// 移除缓存 /// </summary> /// <param name="key">缓存键</param> /// <param name="cacheType">缓存类型(默认是Memcached)</param> /// <returns></returns> public static bool Remove(string key, CacheTypeEnum cacheType = CacheTypeEnum.Default) { if (string.IsNullOrWhiteSpace(key)) { return(false); } switch (cacheType) { case CacheTypeEnum.Memcached: case CacheTypeEnum.Default: default: return(Memcached.DelCache(key)); case CacheTypeEnum.HttpRuntime: return(RuntimeCache.DelCache(key)); } }
public void AddDeliveryClient_CacheOptions_GetClient_ReturnsClient(CacheTypeEnum cacheType) { _serviceCollection.AddDeliveryClient(_correctName, _deliveryOptions); _serviceCollection.AddDeliveryClientCache(_correctName, new DeliveryCacheOptions() { CacheType = cacheType }); var sp = _serviceCollection.BuildServiceProvider(); var factory = sp.GetRequiredService <IDeliveryClientFactory>(); var client = factory.Get(_correctName); client.Should().BeOfType(typeof(DeliveryClientCache)); factory.Should().BeOfType(typeof(NamedDeliveryClientCacheFactory)); client.Should().NotBeNull(); }
public long GetCount(string region, CacheTypeEnum cacheType) { long count = 0L; ConcurrentDictionary <CacheTypeEnum, ConcurrentDictionary <string, byte> > typeKeys; if (_typeCacheKeys.TryGetValue(region, out typeKeys)) { ConcurrentDictionary <string, byte> keys; if (typeKeys.TryGetValue(cacheType, out keys)) { count += keys.Count; } } return(count); }
/// <summary> /// Get list of all keys for specific cache type /// </summary> /// <param name="cacheType"></param> /// <returns></returns> public List <string> GetKeys(string region, CacheTypeEnum cacheType) { List <string> cacheKeys = new List <string>(); ConcurrentDictionary <CacheTypeEnum, ConcurrentDictionary <string, byte> > typeKeys; if (_typeCacheKeys.TryGetValue(region, out typeKeys)) { ConcurrentDictionary <string, byte> keys; if (typeKeys.TryGetValue(cacheType, out keys)) { cacheKeys.AddRange(keys.Keys); } } return(cacheKeys); }
public void AddDeliveryClient_WithNoCache_GetClient(CacheTypeEnum cacheType) { _serviceCollection.AddDeliveryClient(new DeliveryOptions() { ProjectId = Guid.NewGuid().ToString() }); _serviceCollection.AddDeliveryClientCache(new DeliveryCacheOptions() { CacheType = cacheType }); var sp = _serviceCollection.BuildServiceProvider(); var factory = sp.GetRequiredService <IDeliveryClientFactory>(); var client = factory.Get(); client.Should().NotBeNull(); }
public void Add(string region, CacheTypeEnum cacheType, string key, object data, TimeSpan slidingExpiration) { CacheItemPolicy policy = new CacheItemPolicy(); policy.SlidingExpiration = slidingExpiration; if (_absoluteExpiration.HasValue) { policy.AbsoluteExpiration = _absoluteExpiration.Value; } if (_priority.HasValue) { policy.Priority = _priority.Value; } Add(region, cacheType, key, data, policy); }
public void Save(string key, object data, CacheTypeEnum type, int seconds) { if (!Exists(key)) { CacheItemPolicy policy = null; switch (type) { case CacheTypeEnum.AbsoluteExpiration: policy = GetAbsoluteExpirationPolicy(seconds); break; case CacheTypeEnum.SlidingExpiration: policy = GetSlidingExpirationPolicy(seconds); break; } _Cache.Set(key, data, policy); } }
public void GetNamedDeliveryCacheManager_WithWrongName_GetNull(CacheTypeEnum cacheType) { _serviceCollection.AddDeliveryClient(new DeliveryOptions() { ProjectId = Guid.NewGuid().ToString() }); _serviceCollection.AddDeliveryClientCache(new DeliveryCacheOptions() { CacheType = cacheType }); var sp = _serviceCollection.BuildServiceProvider(); var factory = sp.GetRequiredService <IDeliveryClientFactory>(); var result = factory.Get("WrongName"); result.Should().BeNull(); }
public void AddDeliveryNamedClient_CacheWithDeliveryCacheOptions_GetNull(CacheTypeEnum cacheType) { _serviceCollection.AddDeliveryClient("named", new DeliveryOptions() { ProjectId = Guid.NewGuid().ToString() }); _serviceCollection.AddDeliveryClientCache("named", new DeliveryCacheOptions() { CacheType = cacheType }); var sp = _serviceCollection.BuildServiceProvider(); var factory = sp.GetRequiredService <IDeliveryClientFactory>(); var client = factory.Get("WrongName"); client.Should().BeNull(); }
private void AddStoreCache(string storeCode, CacheTypeEnum cacheType, string key, object data, TimeSpan?slidingExpiration, DateTime?absoluteExpiration) { if (slidingExpiration.HasValue && absoluteExpiration.HasValue) { _serviceCache.Add(storeCode, cacheType, key, data, absoluteExpiration.Value, slidingExpiration.Value); } else if (slidingExpiration.HasValue) { _serviceCache.Add(storeCode, cacheType, key, data, slidingExpiration.Value); } else if (absoluteExpiration.HasValue) { _serviceCache.Add(storeCode, cacheType, key, data, absoluteExpiration.Value); } else { _serviceCache.Add(storeCode, cacheType, key, data); } }
public async Task GetItemTypedAsync_ResponseIsCached(CacheTypeEnum cacheType) { const string codename = "codename"; var url = $"items/{codename}"; var item = CreateItemResponse(CreateItem(codename, "original")); var updatedItem = CreateItemResponse(CreateItem(codename, "updated")); var scenarioBuilder = new ScenarioBuilder(cacheType); var scenario = scenarioBuilder.WithResponse(url, item).Build(); var firstResponse = await scenario.CachingClient.GetItemAsync <TestItem>(codename); scenario = scenarioBuilder.WithResponse(url, updatedItem).Build(); var secondResponse = await scenario.CachingClient.GetItemAsync <TestItem>(codename); firstResponse.Should().NotBeNull(); firstResponse.Should().BeEquivalentTo(secondResponse); scenario.GetRequestCount(url).Should().Be(1); }
public void GetNamedDeliveryCacheManager_WithCorrectName_GetNull(CacheTypeEnum cacheType) { var deliveryOptions = new DeliveryCacheOptions { CacheType = cacheType }; var deliveryCacheManagerFactoryOptions = new DeliveryCacheManagerFactoryOptions(); deliveryCacheManagerFactoryOptions.DeliveryCacheOptions.Add(() => deliveryOptions); A.CallTo(() => _deliveryCacheManagerFactoryOptionsMock.Get(_clientName)) .Returns(deliveryCacheManagerFactoryOptions); var deliveryCacheManagerFactory = new DeliveryCacheManagerFactory(_deliveryCacheManagerFactoryOptionsMock, _serviceCollection.BuildServiceProvider()); var result = deliveryCacheManagerFactory.Get("WrongName"); result.Should().BeNull(); }
private void RemoveCacheKey(string cacheKey) { string[] keyPieces = cacheKey.Split('^'); string region = _GLOBAL; CacheTypeEnum cacheType = (CacheTypeEnum)1000; string key; if (keyPieces.Length == 2) { cacheType = (CacheTypeEnum)Convert.ToInt32(keyPieces[0]); key = keyPieces[1]; } else if (keyPieces.Length == 3) { region = keyPieces[0]; cacheType = (CacheTypeEnum)Convert.ToInt32(keyPieces[1]); key = keyPieces[2]; } ConcurrentDictionary <CacheTypeEnum, ConcurrentDictionary <string, byte> > typeKeys; if (_typeCacheKeys.TryGetValue(region, out typeKeys)) { ConcurrentDictionary <string, byte> keys; if (typeKeys.TryGetValue(cacheType, out keys)) { byte value; keys.TryRemove(cacheKey, out value); if (keys.IsEmpty) { typeKeys.TryRemove(cacheType, out keys); if (typeKeys.IsEmpty) { _typeCacheKeys.TryRemove(region, out typeKeys); } } } } }
public static CacheHandler <T> GetCacheHandler <T>(CacheKeyEnum cacheKey) { CacheTypeEnum cacheType = CacheStaticDomain.Instance.CacheTypeMapping[cacheKey]; if (cacheType == CacheTypeEnum.Redis) { return(new RedisCacheHandler <T>()); } else if (cacheType == CacheTypeEnum.LocalCache) { return(new LocalCacheHandler <T>()); } else if (cacheType == CacheTypeEnum.Composite) { return(new DepositeCacheHandler <T>()); } else { throw new NotImplementedException(); } }
private void AddTerminalCache(string storeCode, int registerNumber, CacheTypeEnum cacheType, string key, object data, TimeSpan?slidingExpiration, DateTime?absoluteExpiration) { string terminalKey = BuildTerminalKey(storeCode, registerNumber); if (slidingExpiration.HasValue && absoluteExpiration.HasValue) { _serviceCache.Add(terminalKey, cacheType, key, data, absoluteExpiration.Value, slidingExpiration.Value); } else if (slidingExpiration.HasValue) { _serviceCache.Add(terminalKey, cacheType, key, data, slidingExpiration.Value); } else if (absoluteExpiration.HasValue) { _serviceCache.Add(terminalKey, cacheType, key, data, absoluteExpiration.Value); } else { _serviceCache.Add(terminalKey, cacheType, key, data); } }
/// <summary> /// 实时添加日志并抛出异常 /// </summary> /// <param name="message">提示信息</param> /// <param name="isStackTrace">是否包含调用堆栈</param> /// <param name="cacheTypeEnum">是否缓存</param> public void ThrowReal(string message, bool isStackTrace, CacheTypeEnum cacheTypeEnum) { var value = new DebugPlus { StackTrace = isStackTrace ? new StackTrace() : null, StackFrame = isStackTrace ? null : new StackFrame(1), Message = message }; if (cacheTypeEnum == CacheTypeEnum.None || CheckCache(value, cacheTypeEnum == CacheTypeEnum.Queue)) RealOutput(value); throw new Exception(ExceptionPrefix + message); }
public void InsertCacheUpdateDefered(IUnitOfWork uow, CacheTypeEnum cacheType, string item) { Action deferAction = () => { InsertCacheUpdate(cacheType, item); }; AddOneInvokeBody(uow, deferAction); }
/// <summary> /// 添加日志 /// </summary> /// <param name="message">提示信息</param> /// <param name="isStackTrace">是否包含调用堆栈</param> /// <param name="cacheTypeEnum">缓存类型</param> public void Add(string message, bool isStackTrace, CacheTypeEnum cacheTypeEnum) { DebugPlus value = new DebugPlus { StackTrace = isStackTrace ? new StackTrace() : null, StackFrame = isStackTrace ? null : new StackFrame(1), Message = message }; if (cacheTypeEnum == CacheTypeEnum.None || CheckCache(value, cacheTypeEnum == CacheTypeEnum.Queue)) Output(value); }
/// <summary> /// 实时添加日志 /// </summary> /// <param name="message">提示信息</param> /// <param name="isStackTrace">是否包含调用堆栈</param> /// <param name="cacheTypeEnum">是否缓存</param> public void Real(string message, bool isStackTrace, CacheTypeEnum cacheTypeEnum) { var value = new DebugPlus { StackTrace = isStackTrace ? new StackTrace() : null, StackFrame = isStackTrace ? null : new StackFrame(1), Message = message }; if (_cache == CacheTypeEnum.None || CheckCache(value, _cache == CacheTypeEnum.Queue)) RealOutput(value); }
public void InsertCacheUpdate(CacheTypeEnum cacheType, string item) { try { IList<string> ret = new List<string>(); MethodBase mb = MethodBase.GetCurrentMethod(); _Schema.SQLContext sqlCtx = null; lock (mb) { if (!_Schema.Func.PeerTheSQL(mb.MetadataToken, out sqlCtx)) { sqlCtx = new _Schema.SQLContext(); sqlCtx.Sentence = @"merge CacheUpdate as T using (select @Type,@Item,0, a.ServerIP,a.AppName from CacheUpdateServer a) as S([Type],Item,Updated,CacheServerIP,AppName) on T.[Type]=S.[Type] and T.Item= S.Item and T.CacheServerIP =S.CacheServerIP and T.AppName=S.AppName WHEN MATCHED and T.Updated=1 THEN UPDATE SET Updated = 0, Udt=getdate() WHEN NOT MATCHED THEN INSERT ([Type], Item, Updated, CacheServerIP, AppName, Cdt, Udt) VALUES (S.[Type], S.Item, S.Updated, S.CacheServerIP, S.AppName, getdate(), getdate());"; sqlCtx.Params.Add("Type", new SqlParameter("@Type", SqlDbType.VarChar)); sqlCtx.Params.Add("Item", new SqlParameter("@Item", SqlDbType.VarChar)); _Schema.Func.InsertIntoCache(mb.MetadataToken, sqlCtx); } } sqlCtx.Params["Type"].Value = cacheType.ToString(); sqlCtx.Params["Item"].Value = item; _Schema.SqlHelper.ExecuteNonQuery(_Schema.SqlHelper.ConnectionString_GetData, CommandType.Text, sqlCtx.Sentence, sqlCtx.Params.Values.ToArray<SqlParameter>()); } catch (Exception) { throw; } }
/// <summary> /// 实时添加日志并抛出异常 /// </summary> /// <param name="error">错误异常</param> /// <param name="message">提示信息</param> /// <param name="cacheTypeEnum">是否缓存</param> public void ThrowReal(Exception error, string message, CacheTypeEnum cacheTypeEnum) { if (error != null && error.Message.StartsWith(ExceptionPrefix, StringComparison.Ordinal)) error = null; if (error == null) { if (message != null) ThrowReal(message, true, cacheTypeEnum); } else { var value = new DebugPlus { Exception = error, Message = message }; if (cacheTypeEnum == CacheTypeEnum.None || CheckCache(value, cacheTypeEnum == CacheTypeEnum.Queue)) RealOutput(value); throw error != null ? new Exception(ExceptionPrefix + message, error) : new Exception(ExceptionPrefix + message); } }