protected virtual void TrySet_Value_And_Get_Cached_Value_Should_Succeed() { var cacheKey = $"{_nameSpace}{Guid.NewGuid().ToString()}"; var cacheValue1 = "value1"; var cacheValue2 = "value2"; var first = _provider.TrySet(cacheKey, cacheValue1, _defaultTs); var second = _provider.TrySet(cacheKey, cacheValue2, _defaultTs); Assert.True(first); Assert.False(second); var val = _provider.Get <string>(cacheKey); Assert.True(val.HasValue); Assert.Equal(cacheValue1, val.Value); }
/// <summary> /// Tries the set. /// </summary> /// <returns><c>true</c>, if set was tryed, <c>false</c> otherwise.</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 bool TrySet <T>(string cacheKey, T cacheValue, TimeSpan expiration) { ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); var flag = _distributedCache.TrySet(cacheKey, cacheValue, expiration); if (flag) { //When TrySet succeed in distributed cache, Set(not TrySet) this cache to local cache. _localCache.Set(cacheKey, cacheValue, expiration); } return(flag); }
public IActionResult Get() { var inCache = _cachingProvider.Exists("CAR_IN_CACHE"); if (inCache) { return(Ok(_cachingProvider.Get <Car>("CAR_IN_CACHE").Value)); } else { var carFromProvider = _carProvider.Get(); _cachingProvider.TrySet("CAR_IN_CACHE", carFromProvider, TimeSpan.FromMinutes(1)); return(Ok(carFromProvider)); } }
/// <summary> /// Tries the set. /// </summary> /// <returns><c>true</c>, if set was tryed, <c>false</c> otherwise.</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 bool TrySet <T>(string cacheKey, T cacheValue, TimeSpan expiration) { ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); bool distributedError = false; bool flag = false; try { flag = _distributedCache.TrySet(cacheKey, cacheValue, expiration); } catch (Exception ex) { distributedError = true; LogMessage($"tryset cache key [{cacheKey}] error", ex); } if (flag && !distributedError) { // When we TrySet succeed in distributed cache, we should Set this cache to local cache. // It's mainly to prevent the cache value was changed _localCache.Set(cacheKey, cacheValue, expiration); } // distributed cache occur error, have a try with local cache if (distributedError) { flag = _localCache.TrySet(cacheKey, cacheValue, expiration); } if (flag) { // Here should send message to bus due to cache was set successfully. _busSyncWrap.Execute(() => _bus.Publish(_options.TopicName, new EasyCachingMessage { Id = _cacheId, CacheKeys = new string[] { cacheKey } })); } return(flag); }
/// <summary> /// 当缓存数据不存在则添加,已存在不会添加,添加成功返回true /// </summary> /// <typeparam name="T">缓存数据类型</typeparam> /// <param name="key">缓存键</param> /// <param name="value">值</param> /// <param name="expiration">过期时间间隔</param> public bool TryAdd <T>(string key, T value, TimeSpan?expiration = null) { return(_provider.TrySet(key, value, GetExpiration(expiration))); }
/// <summary> /// Tries the set. /// </summary> /// <typeparam name="T">Type of cache value</typeparam> /// <param name="cacheKey">Cache key</param> /// <param name="cacheValue">Cache value</param> /// <param name="expirationMinutes">Expiration in minutes</param> /// <returns>Determines whether it is successful</returns> public bool TrySet <T>(string cacheKey, T cacheValue, int?expirationMinutes = null) { var timespan = TimeSpan.FromMinutes(expirationMinutes ?? _options.DefaultCacheMinutes); return(_easyCachingProvider.TrySet(cacheKey, cacheValue, timespan)); }
internal void Server_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e) { if (string.IsNullOrEmpty(e.ClientId)) { _logger.LogInformation($"Message: Topic=[{e.ApplicationMessage.Topic }]"); } else { _logger.LogInformation($"Server received {e.ClientId}'s message: Topic=[{e.ApplicationMessage.Topic }],Retain=[{e.ApplicationMessage.Retain}],QualityOfServiceLevel=[{e.ApplicationMessage.QualityOfServiceLevel}]"); if (!lstTopics.ContainsKey(e.ApplicationMessage.Topic)) { lstTopics.Add(e.ApplicationMessage.Topic, 1); Task.Run(() => _serverEx.PublishAsync("$SYS/broker/subscriptions/count", lstTopics.Count.ToString())); } else { lstTopics[e.ApplicationMessage.Topic]++; } if (e.ApplicationMessage.Payload != null) { received += e.ApplicationMessage.Payload.Length; } string topic = e.ApplicationMessage.Topic; var tpary = topic.Split('/', StringSplitOptions.RemoveEmptyEntries); if (tpary.Length >= 3 && tpary[0] == "devices" && _device.Exists(e.ClientId)) { Device device = JudgeOrCreateNewDevice(tpary, _device.Get <Device>(e.ClientId).Value); if (device != null) { Dictionary <string, object> keyValues = new Dictionary <string, object>(); if (tpary.Length >= 4) { string keyname = tpary.Length >= 5 ? tpary[4] : tpary[3]; if (tpary[3].ToLower() == "xml") { try { var xml = new System.Xml.XmlDocument(); xml.LoadXml(e.ApplicationMessage.ConvertPayloadToString()); keyValues.Add(keyname, xml); } catch (Exception ex) { _logger.LogWarning(ex, $"xml data error {topic},{ex.Message}"); } } else if (tpary[3].ToLower() == "binary") { keyValues.Add(keyname, e.ApplicationMessage.Payload); } } else { try { keyValues = e.ApplicationMessage.ConvertPayloadToDictionary(); } catch (Exception ex) { _logger.LogWarning(ex, $"ConvertPayloadToDictionary Error {topic},{ex.Message}"); } } var devx = _device.Get <Device>(e.ClientId); _device.TrySet(e.ClientId, devx.Value, TimeSpan.FromDays(365)); if (tpary[2] == "telemetry") { _queue.PublishTelemetryData(new RawMsg() { DeviceId = device.Id, MsgBody = keyValues, DataSide = DataSide.ClientSide, DataCatalog = DataCatalog.TelemetryData }); } else if (tpary[2] == "attributes") { if (tpary.Length > 3 && tpary[3] == "request") { Task.Run(async() => { await RequestAttributes(tpary, e.ApplicationMessage.ConvertPayloadToDictionary(), device); }); } else { _queue.PublishAttributeData(new RawMsg() { DeviceId = device.Id, MsgBody = keyValues, DataSide = DataSide.ClientSide, DataCatalog = DataCatalog.AttributeData }); } } } } else { Task.Run(async() => { var ss = await _serverEx.GetClientStatusAsync(); ss.FirstOrDefault(t => t.ClientId == e.ClientId)?.DisconnectAsync(); }); } } }
public bool TrySet <T>(string cacheKey, T value, TimeSpan?expiration = null) { expiration = expiration ?? TimeSpan.FromDays(1); return(_provider.TrySet(cacheKey, value, expiration.GetValueOrDefault())); }