Ejemplo n.º 1
0
        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());
        }
Ejemplo n.º 2
0
        public IActionResult GetPerson(int personId)
        {
            if (!_cachingProvider.Exists(personId.ToString()))
            {
                return(BadRequest($"the person with id {personId} does not exist ..."));
            }

            var personString = _cachingProvider.Get <string>(personId.ToString());
            var person       = JsonConvert.DeserializeObject <Person>(personString.ToString());

            Debug.WriteLine(person);

            return(Ok(person));
        }
Ejemplo n.º 3
0
 public Task Execute(IJobExecutionContext context)
 {
     return(Task.Run(async() =>
     {
         //如果中断在mqtt服务器列表中, 则取得最后一次收到消息的时间戳,
         using (var scope = _scopeFactor.CreateScope())
             using (var _dbContext = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>())
             {
                 var clientstatus = await _serverEx.GetClientStatusAsync();
                 clientstatus.ToList().ForEach(cs =>
                 {
                     if (_device.Exists(cs.ClientId))
                     {
                         var dev = _device.Get <Device>(cs.ClientId);
                         var d = _dbContext.Device.FirstOrDefault(d => d.Id == dev.Value.Id);
                         if (d != null)
                         {
                             d.LastActive = cs.LastPacketReceivedTimestamp;
                         }
                     }
                 });
                 //如果超时小于1 就设置为默认300秒
                 var tfx = from d in _dbContext.Device where d.Timeout < 1 select d;
                 tfx.ToList().ForEach(d => d.Timeout = 300);
                 //当前时间减去最后活跃时间如果小于超时时间, 则为在线, 否则就是离线
                 _dbContext.Device.ToList().ForEach(d =>
                 {
                     d.Online = DateTime.Now.Subtract(d.LastActive).TotalSeconds < d.Timeout;
                 });
                 await _dbContext.SaveChangesAsync();
             }
     }));
 }
        protected virtual void SAdd_With_Expiration_Should_Succeed()
        {
            var cacheKey = $"{_nameSpace}-{Guid.NewGuid().ToString()}";

            var res = _provider.SAdd(cacheKey, new List <string> {
                "s1", "s2"
            }, TimeSpan.FromSeconds(1));

            Assert.Equal(2, res);

            System.Threading.Thread.Sleep(1050);

            var flag = _baseProvider.Exists(cacheKey);

            Assert.False(flag);

            _baseProvider.Remove(cacheKey);
        }
Ejemplo n.º 5
0
 public byte[] getItem(string key)
 {
     if (cachingProvider.Exists(key))
     {
         var item = this.cachingProvider.Get <byte[]>(key).Value;
         return(item);
     }
     return(null);
 }
        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));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Exists the specified cacheKey.
        /// </summary>
        /// <returns>The exists.</returns>
        /// <param name="cacheKey">Cache key.</param>
        public bool Exists(string cacheKey)
        {
            ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey));

            var flag = false;

            flag = _localCachingProvider.Exists(cacheKey);

            if (!flag)
            {
                flag = _distributedCachingProvider.Exists(cacheKey);
            }

            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));
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Exists the specified cacheKey.
        /// </summary>
        /// <returns>The exists.</returns>
        /// <param name="cacheKey">Cache key.</param>
        public bool Exists(string cacheKey)
        {
            ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey));
            bool flag;

            try
            {
                flag = _distributedCache.Exists(cacheKey);
                return(flag);
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "Check cache key exists error [{0}] ", cacheKey);
            }

            flag = _localCache.Exists(cacheKey);

            return(flag);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Exists the specified cacheKey.
        /// </summary>
        /// <returns>The exists.</returns>
        /// <param name="cacheKey">Cache key.</param>
        public bool Exists(string cacheKey)
        {
            ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey));
            bool flag;

            // Circuit Breaker may be more better
            try
            {
                flag = _distributedCache.Exists(cacheKey);
                return(flag);
            }
            catch (Exception ex)
            {
                LogMessage($"Check cache key exists error [{cacheKey}] ", ex);
            }

            flag = _localCache.Exists(cacheKey);

            return(flag);
        }
Ejemplo n.º 11
0
 public bool Exists(string cacheKey)
 {
     return(_provider.Exists(cacheKey));
 }
Ejemplo n.º 12
0
 /// <summary>
 /// 是否存在指定键的缓存
 /// </summary>
 /// <param name="key">缓存键</param>
 /// <returns></returns>
 public bool Exists(string key) => _provider.Exists(key);
Ejemplo n.º 13
0
 public void Exists_Cached_Value_Should_Throw_ArgumentNullException_When_CacheKey_IsNullOrWhiteSpace(string cacheKey)
 {
     Assert.Throws <ArgumentNullException>(() => _provider.Exists(cacheKey));
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Exists the specified cacheKey.
        /// </summary>
        /// <returns>The exists.</returns>
        /// <param name="cacheKey">Cache key.</param>
        public bool Exists(string cacheKey)
        {
            ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey));

            return(_distributedCache.Exists(cacheKey));
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Gets a value indicating whether the value associated with the specified key is cached
 /// </summary>
 /// <param name="key">Key of cached item</param>
 /// <returns>True if item already is in cache; otherwise false</returns>
 public bool IsSet(string key)
 {
     return _provider.Exists(key);
 }
Ejemplo n.º 16
0
 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();
             });
         }
     }
 }
Ejemplo n.º 17
0
 /// <summary>
 /// 是否存在指定键的缓存
 /// </summary>
 /// <param name="key">缓存键</param>
 public bool Exists(string key)
 {
     return(_provider.Exists(key));
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Whether the cached value contains the specified cacheKey.
 /// </summary>
 /// <param name="cacheKey">Cache key.</param>
 /// <returns>The exists.</returns>
 public bool Exists(string cacheKey)
 {
     return(_easyCachingProvider.Exists(cacheKey));
 }