/// <summary> /// Get the specified cacheKey. /// </summary> /// <returns>The get.</returns> /// <param name="cacheKey">Cache key.</param> /// <typeparam name="T">The 1st type parameter.</typeparam> public CacheValue <T> Get <T>(string cacheKey) { ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); var cacheValue = _localCache.Get <T>(cacheKey); if (cacheValue.HasValue) { return(cacheValue); } _logger?.LogDebug("local cache can not get the value of {0}", cacheKey); try { cacheValue = _distributedCache.Get <T>(cacheKey); } catch (Exception ex) { _logger?.LogError(ex, "distributed cache get error, [{0}]", cacheKey); } if (cacheValue.HasValue) { TimeSpan ts = GetExpirationFromDistributedProvider(cacheKey); _localCache.Set(cacheKey, cacheValue.Value, ts); return(cacheValue); } _logger?.LogDebug("distributed cache can not get the value of {0}", cacheKey); return(CacheValue <T> .NoValue); }
/// <summary> /// Set the specified key, entry and validFor. /// </summary> /// <returns>The set.</returns> /// <param name="key">Key.</param> /// <param name="entry">Entry.</param> /// <param name="validFor">Valid for.</param> public void Set(string key, IResponseCacheEntry entry, TimeSpan validFor) { var cachedResponse = entry as CachedResponse; if (cachedResponse != null) { _provider.Set( key, new EasyCachingResponse { Created = cachedResponse.Created, StatusCode = cachedResponse.StatusCode, Headers = cachedResponse.Headers.ToDictionary(x => x.Key, x => x.Value.ToArray()), Body = this.GetBytes(cachedResponse.Body) }, validFor); } else { _provider.Set( key, entry, validFor); } }
/// <summary> /// Adds a new item to the cache. /// </summary> /// <param name="cacheKey">key</param> /// <param name="value">value</param> /// <param name="cachePolicy">Defines the expiration mode of the cache item.</param> public void InsertValue(EFCacheKey cacheKey, EFCachedData value, EFCachePolicy cachePolicy) { _readerWriterLockProvider.TryWriteLocked(() => { if (value == null) { value = new EFCachedData { IsNull = true }; } var keyHash = cacheKey.KeyHash; foreach (var rootCacheKey in cacheKey.CacheDependencies) { var items = _easyCachingProvider.Get <HashSet <string> >(rootCacheKey); if (items.IsNull) { _easyCachingProvider.Set(rootCacheKey, new HashSet <string> { keyHash }, cachePolicy.CacheTimeout); } else { items.Value.Add(keyHash); _easyCachingProvider.Set(rootCacheKey, items.Value, cachePolicy.CacheTimeout); } } // We don't support Sliding Expiration at this time. -> https://github.com/dotnetcore/EasyCaching/issues/113 _easyCachingProvider.Set(keyHash, value, cachePolicy.CacheTimeout); }); }
/// <summary> /// Get the specified cacheKey. /// </summary> /// <returns>The get.</returns> /// <param name="cacheKey">Cache key.</param> /// <typeparam name="T">The 1st type parameter.</typeparam> public CacheValue <T> Get <T>(string cacheKey) { ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); var cacheValue = _localCache.Get <T>(cacheKey); if (cacheValue.HasValue) { return(cacheValue); } if (_options.EnableLogging) { _logger.LogTrace($"local cache can not get the value of {cacheKey}"); } cacheValue = _distributedCache.Get <T>(cacheKey); if (cacheValue.HasValue) { //TODO: What about the value of expiration? Form configuration or others? _localCache.Set(cacheKey, cacheValue.Value, TimeSpan.FromSeconds(60)); return(cacheValue); } if (_options.EnableLogging) { _logger.LogTrace($"distributed cache can not get the value of {cacheKey}"); } return(CacheValue <T> .NoValue); }
/// <summary> /// Caches the add action. /// </summary> /// <param name="channel">Channel.</param> /// <param name="value">Value.</param> private void CacheAddAction(RedisChannel channel, RedisValue value) { var message = _serializer.Deserialize <EasyCachingMessage>(value); //TODO : add local cache _localCachingProvider.Set(message.CacheKey, message.CacheValue, message.Expiration); }
/// <summary> /// Proceeds the able. /// </summary> /// <param name="invocation">Invocation.</param> private void ProceedAble(IInvocation invocation) { var serviceMethod = invocation.Method ?? invocation.MethodInvocationTarget; if (serviceMethod.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(EasyCachingAbleAttribute)) is EasyCachingAbleAttribute attribute) { var cacheKey = _keyGenerator.GetCacheKey(serviceMethod, invocation.Arguments, attribute.CacheKeyPrefix); var cacheValue = _cacheProvider.Get <object>(cacheKey); if (cacheValue.HasValue) { invocation.ReturnValue = cacheValue.Value; } else { // Invoke the method if we don't have a cache hit invocation.Proceed(); if (!string.IsNullOrWhiteSpace(cacheKey) && invocation.ReturnValue != null) { _cacheProvider.Set(cacheKey, invocation.ReturnValue, TimeSpan.FromSeconds(attribute.Expiration)); } } } else { // Invoke the method if we don't have EasyCachingAbleAttribute invocation.Proceed(); } }
/// <summary> /// Set the specified key, entry and validFor. /// </summary> /// <returns>The set.</returns> /// <param name="key">Key.</param> /// <param name="entry">Entry.</param> /// <param name="validFor">Valid for.</param> public void Set(string key, IResponseCacheEntry entry, TimeSpan validFor) { if (entry is CachedResponse cachedResponse) { var segmentStream = new SegmentWriteStream(StreamUtilities.BodySegmentSize); cachedResponse.Body.CopyTo(segmentStream); _provider.Set( key, new EasyCachingResponse { Created = cachedResponse.Created, StatusCode = cachedResponse.StatusCode, Headers = cachedResponse.Headers, BodySegments = segmentStream.GetSegments(), BodyLength = segmentStream.Length }, validFor); } else { _provider.Set( key, entry, validFor); } }
/// <summary> /// Adds the specified key and object to the cache /// </summary> /// <param name="key">Key of cached item</param> /// <param name="data">Value for caching</param> /// <param name="cacheTime">Cache time in minutes</param> public void Set(string key, object data, int cacheTime) { if (cacheTime <= 0) return; _provider.Set(key, data, TimeSpan.FromMinutes(cacheTime)); }
public void Bet(Bet bet) { var allRoulettes = this.GetAll(); var openRoulette = allRoulettes.FirstOrDefault(x => x.IsOpen); openRoulette.Bets.Add(bet); EasyCachingProvider.Set(Key + openRoulette.Id, openRoulette, TimeSpan.FromDays(365)); }
/// <summary> /// 新增缓存 /// </summary> /// <param name="key">key</param> /// <param name="data">缓存值</param> /// <param name="cacheTime">缓存时间(单位分钟)。如果为0则不缓存,如果为null则用默认时间</param> public void Set(string key, object data, int?cacheTime = null) { if (cacheTime <= 0) { return; } _provider.Set(key, data, TimeSpan.FromMinutes(cacheTime ?? HbCrmCachingDefaults.CacheTime)); }
/// <summary> /// Proceeds the able. /// </summary> /// <param name="invocation">Invocation.</param> private void ProceedAble(IInvocation invocation) { var serviceMethod = invocation.Method ?? invocation.MethodInvocationTarget; if (serviceMethod.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(EasyCachingAbleAttribute)) is EasyCachingAbleAttribute attribute) { var returnType = serviceMethod.IsReturnTask() ? serviceMethod.ReturnType.GetGenericArguments().First() : serviceMethod.ReturnType; var cacheKey = _keyGenerator.GetCacheKey(serviceMethod, invocation.Arguments, attribute.CacheKeyPrefix); var cacheValue = (_cacheProvider.GetAsync(cacheKey, returnType)).GetAwaiter().GetResult(); if (cacheValue != null) { if (serviceMethod.IsReturnTask()) { invocation.ReturnValue = TypeofTaskResultMethod.GetOrAdd(returnType, t => typeof(Task).GetMethods().First(p => p.Name == "FromResult" && p.ContainsGenericParameters).MakeGenericMethod(returnType)).Invoke(null, new object[] { cacheValue }); } else { invocation.ReturnValue = cacheValue; } } else { // Invoke the method if we don't have a cache hit invocation.Proceed(); if (!string.IsNullOrWhiteSpace(cacheKey) && invocation.ReturnValue != null) { if (serviceMethod.IsReturnTask()) { //get the result var returnValue = invocation.UnwrapAsyncReturnValue().Result; _cacheProvider.Set(cacheKey, returnValue, TimeSpan.FromSeconds(attribute.Expiration)); } else { _cacheProvider.Set(cacheKey, invocation.ReturnValue, TimeSpan.FromSeconds(attribute.Expiration)); } } } } else { // Invoke the method if we don't have EasyCachingAbleAttribute invocation.Proceed(); } }
public T Get <T>(string key, Func <T> acquire, int?cacheTime = null) { if (_provider.Exists(key)) { return(_provider.Get <T>(key).Value); } if ((cacheTime ?? CachingDefaultSettings.CacheTime) > 0) { _provider.Set(key, acquire, TimeSpan.FromMinutes(cacheTime ?? CachingDefaultSettings.CacheTime)); } return(acquire()); }
public void Add(string key, T value, TimeSpan ttl, string region) { var cacheKey = $"{region}:{key}"; if (!_options.EnableHybrid) { _provider.Set(cacheKey, value, ttl); } else { _hybridProvider.Set(cacheKey, value, ttl); } }
/// <summary> /// Get the specified cacheKey. /// </summary> /// <returns>The get.</returns> /// <param name="cacheKey">Cache key.</param> /// <typeparam name="T">The 1st type parameter.</typeparam> public CacheValue <T> Get <T>(string cacheKey) { ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); var cacheValue = _localCache.Get <T>(cacheKey); if (cacheValue.HasValue) { return(cacheValue); } LogMessage($"local cache can not get the value of {cacheKey}"); // Circuit Breaker may be more better try { cacheValue = _distributedCache.Get <T>(cacheKey); } catch (Exception ex) { LogMessage($"distributed cache get error, [{cacheKey}]", ex); } if (cacheValue.HasValue) { TimeSpan ts = TimeSpan.Zero; try { ts = _distributedCache.GetExpiration(cacheKey); } catch { } if (ts <= TimeSpan.Zero) { ts = TimeSpan.FromSeconds(_options.DefaultExpirationForTtlFailed); } _localCache.Set(cacheKey, cacheValue.Value, ts); return(cacheValue); } LogMessage($"distributed cache can not get the value of {cacheKey}"); return(CacheValue <T> .NoValue); }
public IActionResult AddPerson(Person person) { if (_cachingProvider.Exists(person.Id.ToString())) { return(BadRequest("person with the same key already exists ...")); } var personJson = JsonConvert.SerializeObject(person); _cachingProvider.Set(person.Id.ToString(), personJson, TimeSpan.FromDays(1)); Debug.WriteLine($"person added: {person}"); return(Ok(person)); }
public async Task <ActionResult <IEnumerable <string> > > Get() { _logger.LogInformation("正在调用接口 GET api/values "); var client = _httpClientFactory.CreateClient("cnblogs"); var result = await client.GetStringAsync("xlgwr"); //Remove _provider.Remove("demo"); //Set _provider.Set("demo", result, TimeSpan.FromMinutes(1)); return(new string[] { "value1", "value2", result }); }
/// <summary> /// 从缓存中获取数据,如果不存在,则执行获取数据操作并添加到缓存中 /// </summary> /// <typeparam name="T">缓存数据类型</typeparam> /// <param name="key">缓存键</param> /// <param name="func">获取数据操作</param> /// <param name="expiration">过期时间间隔</param> public T Get <T>(string key, Func <T> func, TimeSpan?expiration = null) { if (_provider.Exists(key)) { return(_provider.Get <T>(key).Value); } var value = func(); if (value == null) { return(default(T)); } _provider.Set(key, value, GetExpiration(expiration)); return(value); }
public string Get(string str) { var method = str.ToLower(); switch (method) { case "get": var res = _provider.Get("demo", () => "456", TimeSpan.FromMinutes(1)); return($"cached value : {res}"); case "set": _provider.Set("demo", "123", TimeSpan.FromMinutes(1)); return("seted"); case "remove": _provider.Remove("demo"); return("removed"); case "getcount": var count = _provider.GetCount(); return($"{count}"); default: return("default"); } }
/// <summary> /// Get the specified cacheKey. /// </summary> /// <returns>The get.</returns> /// <param name="cacheKey">Cache key.</param> /// <typeparam name="T">The 1st type parameter.</typeparam> public CacheValue <T> Get <T>(string cacheKey) { ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); var cacheValue = _localCache.Get <T>(cacheKey); if (cacheValue.HasValue) { return(cacheValue); } if (_options.EnableLogging) { _logger.LogTrace($"local cache can not get the value of {cacheKey}"); } cacheValue = _distributedCache.Get <T>(cacheKey); if (cacheValue.HasValue) { TimeSpan ts = TimeSpan.Zero; try { ts = _distributedCache.GetExpiration(cacheKey); } catch { } if (ts <= TimeSpan.Zero) { ts = TimeSpan.FromSeconds(_options.DefaultExpirationForTtlFailed); } _localCache.Set(cacheKey, cacheValue.Value, ts); return(cacheValue); } if (_options.EnableLogging) { _logger.LogTrace($"distributed cache can not get the value of {cacheKey}"); } return(CacheValue <T> .NoValue); }
public IActionResult PutItemsInBasket(int id, Models.Basket basket) { basket.Id = id; var serializedBasket = JsonConvert.SerializeObject(basket); cachingProvider.Set("Basket_" + id, serializedBasket, TimeSpan.FromDays(15)); return(NoContent()); }
private void DeviceDiscoveredHandler(IBleAdapter sender, BleDeviceEventArgs args) { var device = args.Device; var deviceId = device.Id; var pd = new ProxiedBleDevice(sender, device); _cachingProvider.Set(GetDeviceCacheKey(deviceId), pd, DiscoveredDeviceCachingTime); }
/// <summary> /// Set the specified cacheKey, cacheValue and expiration. /// </summary> /// <returns>The set.</returns> /// <param name="cacheKey">Cache key.</param> /// <param name="cacheValue">Cache value.</param> /// <param name="expiration">Expiration.</param> /// <typeparam name="T">The 1st type parameter.</typeparam> public void Set <T>(string cacheKey, T cacheValue, TimeSpan expiration) where T : class { ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); ArgumentCheck.NotNull(cacheValue, nameof(cacheValue)); ArgumentCheck.NotNegativeOrZero(expiration, nameof(expiration)); _localCachingProvider.Set(cacheKey, cacheValue, expiration); _distributedCachingProvider.Set(cacheKey, cacheValue, expiration); }
/// <summary> /// Set the the exporation of specify cachekey. /// </summary>> /// <param name="cacheKey">Cache key.</param> /// <param name="expirationMinutes">Expiration in minutes</param> public void SetExpiration(string cacheKey, int?expirationMinutes = null) { var timespan = TimeSpan.FromMinutes(expirationMinutes ?? _options.DefaultCacheMinutes); switch (_options.ProviderType) { case CachingProviderType.InMemory: var cacheValue = _easyCachingProvider.Get <dynamic>(cacheKey); _easyCachingProvider.Set(cacheKey, cacheValue, timespan); break; case CachingProviderType.Redis: _redisCachingProvider.KeyExpire(cacheKey, Convert.ToInt32(timespan.TotalSeconds)); break; default: throw new NotSupportedException($"{nameof(IHybridCachingProvider)} dose not support {nameof(SetExpiration)} method"); } }
protected virtual void Evict_Should_Succeed() { System.Reflection.MethodInfo method = typeof(CastleExampleService).GetMethod("EvictTest"); var key = _keyGenerator.GetCacheKey(method, null, "CastleExample"); _cachingProvider.Set(key, "AAA", TimeSpan.FromSeconds(30)); var value = _cachingProvider.Get <string>(key); Assert.Equal("AAA", value.Value); _service.EvictTest(); var after = _cachingProvider.Get <string>(key); Assert.False(after.HasValue); }
/// <summary> /// Set the specified cacheKey, cacheValue and expiration. /// </summary> /// <param name="cacheKey">Cache key.</param> /// <param name="cacheValue">Cache value.</param> /// <param name="expiration">Expiration.</param> /// <typeparam name="T">The 1st type parameter.</typeparam> public void Set <T>(string cacheKey, T cacheValue, TimeSpan expiration) { ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); _localCache.Set(cacheKey, cacheValue, expiration); _distributedCache.Set(cacheKey, cacheValue, expiration); //When create/update cache, send message to bus so that other clients can remove it. _bus.Publish(_options.TopicName, new EasyCachingMessage { Id = _cacheId, CacheKeys = new string[] { cacheKey } }); }
public void Sec_Set_Value_And_Get_Cached_Value_Should_Succeed() { var cacheKey = Guid.NewGuid().ToString(); var cacheValue = "value"; _secondProvider.Set(cacheKey, cacheValue, _defaultTs); var val = _secondProvider.Get <string>(cacheKey); Assert.True(val.HasValue); Assert.Equal(cacheValue, val.Value); }
public async Task <ApiResult <Dictionary <string, string> > > Current(string lang) { lang = lang?.ToLower(); var _cachedi18n = await _cachingprovider.GetAsync <BaseI18N[]>("i18n"); var i18n = _cachedi18n?.Value; if (i18n == null) { i18n = _context.BaseI18Ns.ToArray(); if (i18n.Length == 0) { await _dBInitializer.SeedI18N(); i18n = _context.BaseI18Ns.ToArray(); } _cachingprovider.Set <BaseI18N[]>("i18n", i18n, TimeSpan.FromMinutes(5)); } switch (lang) { case "el-gr": return(new ApiResult <Dictionary <string, string> >(ApiCode.Success, "OK", i18n.Select(c => new { c.KeyName, c.ValueENGR }).ToDictionary(x => x.KeyName, y => y.ValueENGR))); case "en-us": return(new ApiResult <Dictionary <string, string> >(ApiCode.Success, "OK", i18n.Select(c => new { c.KeyName, c.ValueENUS }).ToDictionary(x => x.KeyName, y => y.ValueENUS))); case "fr-fr": return(new ApiResult <Dictionary <string, string> >(ApiCode.Success, "OK", i18n.Select(c => new { c.KeyName, c.ValueFRFR }).ToDictionary(x => x.KeyName, y => y.ValueFRFR))); case "hr-hr": return(new ApiResult <Dictionary <string, string> >(ApiCode.Success, "OK", i18n.Select(c => new { c.KeyName, c.ValueHRHR }).ToDictionary(x => x.KeyName, y => y.ValueHRHR))); case "ko-kr": return(new ApiResult <Dictionary <string, string> >(ApiCode.Success, "OK", i18n.Select(c => new { c.KeyName, c.ValueKOKR }).ToDictionary(x => x.KeyName, y => y.ValueKOKR))); case "pl-pl": return(new ApiResult <Dictionary <string, string> >(ApiCode.Success, "OK", i18n.Select(c => new { c.KeyName, c.ValuePLPL }).ToDictionary(x => x.KeyName, y => y.ValuePLPL))); case "sl-sl": return(new ApiResult <Dictionary <string, string> >(ApiCode.Success, "OK", i18n.Select(c => new { c.KeyName, c.ValueSLSL }).ToDictionary(x => x.KeyName, y => y.ValueSLSL))); case "tr-tr": return(new ApiResult <Dictionary <string, string> >(ApiCode.Success, "OK", i18n.Select(c => new { c.KeyName, c.ValueTRTR }).ToDictionary(x => x.KeyName, y => y.ValueTRTR))); case "zh-tw": return(new ApiResult <Dictionary <string, string> >(ApiCode.Success, "OK", i18n.Select(c => new { c.KeyName, c.ValueZHTW }).ToDictionary(x => x.KeyName, y => y.ValueZHTW))); case "zh-cn": return(new ApiResult <Dictionary <string, string> >(ApiCode.Success, "OK", i18n.Select(c => new { c.KeyName, c.ValueZHCN }).ToDictionary(x => x.KeyName, y => y.ValueZHCN))); } return(new ApiResult <Dictionary <string, string> >(ApiCode.Success, "OK", i18n.Select(c => new { c.KeyName, c.ValueZHCN }).ToDictionary(x => x.KeyName, y => y.ValueZHCN))); }
protected virtual void Set_Value_And_Get_Cached_Value_Should_Succeed() { var cacheKey = $"{_nameSpace}{Guid.NewGuid().ToString()}"; var cacheValue = "value"; _provider.Set(cacheKey, cacheValue, _defaultTs); var val = _provider.Get <string>(cacheKey); Assert.True(val.HasValue); Assert.Equal(cacheValue, val.Value); }
public async Task CreateNewOrReplaceExisting(RecipeDetails recipeDetails) { var key = recipeDetails.Id.Value .ToDictionaryKey(nameof(RecipeDetails)); if (_cachingProvider.Exists(key)) { _cachingProvider.Remove(key); } _cachingProvider.Set(key, recipeDetails, TimeSpan.FromDays(30)); }
/// <summary> /// 取得缓存数据(同步) /// </summary> /// <returns>数据</returns> public IList <T> GetCacheData() { var cacheList = _provider.Get <List <T> >(_cacheKey); if (!cacheList.HasValue) { // 全量取出 var dataList = _repository.Get().ToList(); _provider.Set(_cacheKey, dataList, TimeSpan.FromSeconds(_cachingOption.ExpireSpan)); return(dataList); } return(cacheList.Value); }