Ejemplo n.º 1
0
        /// <summary>
        /// Get the specified cacheKey, dataRetriever and expiration.
        /// </summary>
        /// <returns>The get.</returns>
        /// <param name="cacheKey">Cache key.</param>
        /// <param name="dataRetriever">Data retriever.</param>
        /// <param name="expiration">Expiration.</param>
        /// <typeparam name="T">The 1st type parameter.</typeparam>
        public CacheValue <T> Get <T>(string cacheKey, Func <T> dataRetriever, TimeSpan expiration) where T : class
        {
            ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey));
            ArgumentCheck.NotNegativeOrZero(expiration, nameof(expiration));

            var value = _localCachingProvider.Get <T>(cacheKey);

            if (value.HasValue)
            {
                return(value);
            }

            value = _distributedCachingProvider.Get <T>(cacheKey);

            if (value.HasValue)
            {
                return(value);
            }

            var item = dataRetriever?.Invoke();

            if (item != null)
            {
                Set(cacheKey, item, expiration);
                return(new CacheValue <T>(item, true));
            }
            else
            {
                //TODO : Set a null value to cache!!

                return(CacheValue <T> .NoValue);
            }
        }
Ejemplo n.º 2
0
        /// <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);
        }
Ejemplo n.º 3
0
        /// <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);
            });
        }
Ejemplo n.º 4
0
        /// <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);
        }
Ejemplo n.º 5
0
        public T Find(string id)
        {
            var a = _provider.Get <T>(id);

            if (!a.IsNull)
            {
                return(a.Value);
            }
            return(null);
        }
Ejemplo n.º 6
0
        protected virtual void Put_Should_Succeed()
        {
            var str = _service.PutTest(1);

            System.Reflection.MethodInfo method = typeof(CastleExampleService).GetMethod("PutTest");

            var key = _keyGenerator.GetCacheKey(method, new object[] { 1, "123" }, "CastleExample");

            var value = _cachingProvider.Get <string>(key);

            Assert.True(value.HasValue);
            Assert.Equal("PutTest-1", value.Value);
        }
Ejemplo n.º 7
0
        /// <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);
        }
Ejemplo n.º 8
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();
             }
     }));
 }
 public List <Todo> GetAll()
 {
     try
     {
         var cacheValue = _provider.Get <string>("TODO");
         var output     = new List <Todo>();;
         if (cacheValue.HasValue)
         {
             output = JsonConvert.DeserializeObject <List <Todo> >(cacheValue.Value);
         }
         else
         {
             // Get data from DB and Add to Cache
             output.Add(new Todo {
                 Id = 1, Title = "Title 1"
             });
             output.Add(new Todo {
                 Id = 2, Title = "Title 2"
             });
             string json = JsonConvert.SerializeObject(output);
             SetItemToCache(json, "TODO");
         }
         return(output.OrderByDescending(p => p.Id).ToList());
     }
     catch (Exception ex)
     {
         throw new ArgumentException(ex.Message);
     }
 }
Ejemplo n.º 10
0
        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");
            }
        }
Ejemplo n.º 11
0
        /// <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();
            }
        }
Ejemplo n.º 12
0
        public void GetSync_DistributedCacheHasValue_SetLocalWithDefaultOrDistributedExpiration(int distributedExpirationMinutes, int setLocalExpirationMinutes)
        {
            var(hybridProvider, fakeLocalProvider, fakeDistributedProvider) = CreateFakeHybridProvider();
            var localExpiration      = TimeSpan.Zero;
            var distributeExpiration = TimeSpan.FromMinutes(distributedExpirationMinutes);
            var cacheKey             = GetUniqueCacheKey();

            A.CallTo(() => fakeLocalProvider.GetExpiration(cacheKey)).Returns(localExpiration);
            A.CallTo(() => fakeLocalProvider.Get <string>(cacheKey))
            .Returns(CacheValue <string> .NoValue);

            A.CallTo(() => fakeDistributedProvider.GetExpiration(cacheKey)).Returns(distributeExpiration);
            A.CallTo(() => fakeDistributedProvider.Get <string>(cacheKey))
            .Returns(new CacheValue <string>("cachedValue", true));


            var res = hybridProvider.Get <string>(cacheKey);


            Assert.NotNull(res.Value);
            Assert.Equal("cachedValue", res.Value);

            A.CallTo(() => fakeDistributedProvider.GetExpiration(cacheKey)).MustHaveHappenedOnceExactly();
            A.CallTo(() => fakeLocalProvider.Set(cacheKey, "cachedValue", TimeSpan.FromMinutes(setLocalExpirationMinutes)))
            .MustHaveHappenedOnceExactly();
        }
Ejemplo n.º 13
0
        public IActionResult GetItemsFromBasket(int id)
        {
            var result           = cachingProvider.Get <string>("Basket_" + id.ToString());
            var serializedResult = JsonConvert.DeserializeObject(result.ToString());

            return(Ok(serializedResult));
        }
Ejemplo n.º 14
0
        /// <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);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Get a cached item. If it's not in the cache yet, then load and cache it
        /// </summary>
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="key">Cache key</param>
        /// <param name="acquire">Function to load item if it's not in the cache yet</param>
        /// <param name="cacheTime">Cache time in minutes; pass 0 to do not cache; pass null to use the default time</param>
        /// <returns>The cached value associated with the specified key</returns>
        public T Get<T>(string key, Func<T> acquire, int? cacheTime = null)
        {
            if (cacheTime <= 0)
                return acquire();

            return _provider.Get(key, acquire, TimeSpan.FromMinutes(cacheTime ?? AppCachingDefaults.CacheTime))
                .Value;
        }
Ejemplo n.º 16
0
        public Roulette GetById(string Id)
        {
            var item = _cachingProvider.Get <Roulette>(Key + Id);

            if (!item.HasValue)
            {
                return(null);
            }
            return(item.Value);
        }
        public IActionResult getAllRoulettes()
        {
            var    actualRoulettes  = cachingProvider.Get <List <Roulette> >("Roulettes");
            String roulettesSummary = "";

            if (actualRoulettes.Value != null)
            {
                for (int i = 0; i < actualRoulettes.Value.Count; i++)
                {
                    Roulette actualRoulette = actualRoulettes.Value[i];
                    roulettesSummary += "\n id de ruleta: " + actualRoulette.rouletteId + "\n ¿la ruleta está activa?: " + actualRoulette.isActive;
                }
                return(Ok("Bienvenido a Good Charm Casino, aquí puedes crear una ruleta y apostar. \n Ruletas actuales: " + roulettesSummary));
            }
            else
            {
                return(Ok(roulettesSummary));
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 获取缓存项。如果它还不在缓存中,则加载并缓存它
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="acquire"></param>
        /// <param name="cacheTime"></param>
        /// <returns>y</returns>
        public T Get <T>(string key, Func <T> acquire, int?cacheTime = null)
        {
            if (cacheTime <= 0)
            {
                return(acquire());
            }

            return(_provider.Get(key, acquire, TimeSpan.FromMinutes(cacheTime ?? CachingDefaults.CacheTime))
                   .Value);
        }
Ejemplo n.º 19
0
        public byte[]? Get(string key)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            var result = _easyCachingProvider.Get <byte[]>(key);

            return((!result.HasValue || result.IsNull) ? null : result.Value);
        }
Ejemplo n.º 20
0
        public Roulette GetById(string Id)
        {
            var item = _cachingProvider.Get <Roulette>($"{REDIS_KEY}{Id}");

            if (!item.HasValue)
            {
                return(null);
            }

            return(item.Value);
        }
Ejemplo n.º 21
0
        public void Disable_Read_And_Disable_Write_DeepClone_Should_Succeed()
        {
            var cacheKey = Guid.NewGuid().ToString();

            var cacheValue = new MySettingForCaching {
                Name = "catcherwong"
            };

            _m3.Set(cacheKey, cacheValue, _defaultTs);

            cacheValue.Name = "afterset";

            var res = _m3.Get <MySettingForCaching>(cacheKey);

            res.Value.Name = "kobe";

            var res2 = _m3.Get <MySettingForCaching>(cacheKey);

            Assert.Equal("kobe", res2.Value.Name);
        }
Ejemplo n.º 22
0
        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);
        }
Ejemplo n.º 23
0
        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);
        }
Ejemplo n.º 24
0
        /// <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);
        }
Ejemplo n.º 25
0
 public UserCaching GetUser(Guid userId, IEasyCachingProvider _easyCaching)
 {
     try
     {
         var userJson        = _easyCaching.Get <string>(userId.ToString()).Value;
         var userDeserialize = JsonConvert.DeserializeObject <UserCaching>(userJson);
         return(JsonConvert.DeserializeObject <UserCaching>(userJson));
     }
     catch (Exception e)
     {
     }
     return(new UserCaching());
 }
Ejemplo n.º 26
0
        public async Task <JsonResult> GetAll()
        {
            var peopleCache = _compCacheProvider.Get <List <Person> >("peopleCollection");

            if (!peopleCache.HasValue)
            {
                var srcCollection = _peopleDb.People.ToList();
                _compCacheProvider.Set("peopleCollection", srcCollection, TimeSpan.FromSeconds(15));
                return(new JsonResult(srcCollection));
            }

            return(new JsonResult(peopleCache.Value));
        }
Ejemplo n.º 27
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.º 28
0
        public void Multi_Instance_Set_And_Get_Should_Succeed()
        {
            var cacheKey1 = "named-provider-1";
            var cacheKey2 = "named-provider-2";

            var value1 = Guid.NewGuid().ToString();
            var value2 = Guid.NewGuid().ToString("N");

            _provider.Set(cacheKey1, value1, _defaultTs);
            _secondProvider.Set(cacheKey2, value2, _defaultTs);

            var p1 = _provider.Get <string>(cacheKey1);
            var p2 = _provider.Get <string>(cacheKey2);

            var s1 = _secondProvider.Get <string>(cacheKey1);
            var s2 = _secondProvider.Get <string>(cacheKey2);

            Assert.Equal(value1, p1.Value);
            Assert.False(p2.HasValue);

            Assert.False(s1.HasValue);
            Assert.Equal(value2, s2.Value);
        }
Ejemplo n.º 29
0
 public void SetUser(UserCaching user, IEasyCachingProvider _easyCaching)
 {
     try
     {
         var isExist = _easyCaching.Get <string>(user.Id.ToString()).HasValue;
         if (!isExist)
         {
             var userJson = JsonConvert.SerializeObject(user);
             _easyCaching.Set(user.Id.ToString(), userJson, TimeSpan.FromDays(100));
         }
     }
     catch
     { }
 }
Ejemplo n.º 30
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));
        }