// Internal for unit testing
    internal DistributedCacheEntryOptions GetDistributedCacheEntryOptions()
    {
        var hasEvictionCriteria = false;
        var options             = new DistributedCacheEntryOptions();

        if (ExpiresOn != null)
        {
            hasEvictionCriteria = true;
            options.SetAbsoluteExpiration(ExpiresOn.Value);
        }

        if (ExpiresAfter != null)
        {
            hasEvictionCriteria = true;
            options.SetAbsoluteExpiration(ExpiresAfter.Value);
        }

        if (ExpiresSliding != null)
        {
            hasEvictionCriteria = true;
            options.SetSlidingExpiration(ExpiresSliding.Value);
        }

        if (!hasEvictionCriteria)
        {
            options.SetSlidingExpiration(DefaultExpiration);
        }

        return(options);
    }
Exemple #2
0
        public async Task AddToCache(TreeNode <NavigationNode> tree, string cacheKey)
        {
            var options = new DistributedCacheEntryOptions();

            options.SetSlidingExpiration(TimeSpan.FromSeconds(_options.CacheDurationInSeconds));
            await _cache.SetAsync <TreeNode <NavigationNode> >(cacheKey, tree, options);
        }
        /// <summary>
        /// 异步获取或刷新在线用户信息
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns>在线用户信息</returns>
        public async Task <OnlineUser> GetOrRefreshAsync(string userName)
        {
            string key = $"Identity_OnlineUser_{userName}";

            DistributedCacheEntryOptions options = new DistributedCacheEntryOptions();

            options.SetSlidingExpiration(TimeSpan.FromMinutes(30));
            return(await _cache.GetAsync <OnlineUser>(key,
                                                      () =>
            {
                return ServiceLocator.Instance.ExcuteScopedWorkAsync <OnlineUser>(async provider =>
                {
                    UserManager <TUser> userManager = provider.GetService <UserManager <TUser> >();
                    TUser user = await userManager.FindByNameAsync(userName);
                    if (user == null)
                    {
                        return null;
                    }
                    IList <string> roles = await userManager.GetRolesAsync(user);

                    RoleManager <TRole> roleManager = provider.GetService <RoleManager <TRole> >();
                    bool isAdmin = roleManager.Roles.Any(m => roles.Contains(m.Name) && m.IsAdmin);

                    return GetOnlineUser(user, roles.ToArray(), isAdmin);
                });
            },
                                                      options));
        }
        public async Task Set(string key, object value, int expirationInSeconds)
        {
            var distributedOptions = new DistributedCacheEntryOptions(); // create options object

            distributedOptions.SetSlidingExpiration(TimeSpan.FromSeconds(_redisSettings.Timeout));
            await _redisDB.SetStringAsync(string.Format(Constant.RedisFormat, _redisSettings.Category, key), JsonConvert.SerializeObject(value), distributedOptions);
        }
Exemple #5
0
        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <param name="value">缓存Value</param>
        /// <param name="expiration">过期时间</param>
        /// <param name="isSliding">是否滑动过期</param>
        /// <returns></returns>
        public bool Add(string key, object value, TimeSpan expiration, bool isSliding = false)
        {
            if (null == key)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (null == value)
            {
                throw new ArgumentNullException(nameof(value));
            }

            var data   = _serializer.Serialize(value);
            var option = new DistributedCacheEntryOptions();

            if (true == isSliding)
            {
                this._cache.Set(key, data, option.SetSlidingExpiration(expiration));
            }
            else
            {
                this._cache.Set(key, data, option.SetAbsoluteExpiration(expiration));
            }

            return(Exists(key));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="key"></param>
        /// <param name="tokenValue"></param>
        /// <returns></returns>
        public Task RenewAsync(string key, string tokenValue)
        {
            DistributedCacheEntryOptions options = new DistributedCacheEntryOptions();

            options.SetSlidingExpiration(TimeSpan.FromSeconds(accessTokenOptions.Expires));
            return(cache.SetAsync($"{KeyPrefix}{key}", tokenValue.ToBytes(), options));
        }
        public ActionResult <Customer> GetCustomerDetails()
        {
            List <Customer> cust;
            string          key = Consts.RedisGetCustomer;

            try
            {
                if (string.IsNullOrEmpty(_distributedCache.GetString(key)))
                {
                    cust = (List <Customer>)_blCustomerDetails.GetCustomerDetails();
                    var option = new DistributedCacheEntryOptions();
                    option.SetSlidingExpiration(TimeSpan.FromMinutes(1));
                    _distributedCache.SetString(key, System.Text.Json.JsonSerializer.Serialize <List <Customer> >(cust), option);
                }
                else
                {
                    cust = System.Text.Json.JsonSerializer.Deserialize <List <Customer> >(_distributedCache.GetString(key));
                }
            }
            catch (StackExchange.Redis.RedisConnectionException)
            {
                cust = (List <Customer>)_blCustomerDetails.GetCustomerDetails();
            }
            return(Ok(cust));
        }
Exemple #8
0
 public DataService(ProgenyDbContext context, IDistributedCache cache)
 {
     _context = context;
     _cache   = cache;
     _cacheOptions.SetAbsoluteExpiration(new System.TimeSpan(0, 5, 0));          // Expire after 5 minutes.
     _cacheOptionsSliding.SetSlidingExpiration(new System.TimeSpan(7, 0, 0, 0)); // Expire after a week.
 }
Exemple #9
0
        public static void Main()
        {
            var configurationBuilder = new ConfigurationBuilder();

            configurationBuilder
            .AddJsonFile("config.json")
            .AddEnvironmentVariables();
            var configuration = configurationBuilder.Build();

            _cacheEntryOptions = new DistributedCacheEntryOptions();
            _cacheEntryOptions.SetSlidingExpiration(TimeSpan.FromSeconds(10));

            var cache = new SqlServerCache(new SqlServerCacheOptions()
            {
                ConnectionString = configuration["ConnectionString"],
                SchemaName       = configuration["SchemaName"],
                TableName        = configuration["TableName"]
            });

            SetKey(cache, "0");

            PeriodicallyReadKey(cache, TimeSpan.FromSeconds(1));

            PeriodciallyRemoveKey(cache, TimeSpan.FromSeconds(11));

            PeriodciallySetKey(cache, TimeSpan.FromSeconds(13));

            Console.ReadLine();
            Console.WriteLine("Shutting down");
        }
        private DistributedCacheEntryOptions BuildDistributedCacheEntryOptions(object expiration = null, bool isAbsoluteExpiration = false)
        {
            var options = new DistributedCacheEntryOptions();

            if (expiration != null)
            {
                if (expiration is TimeSpan)
                {
                    if (isAbsoluteExpiration)
                    {
                        options.SetAbsoluteExpiration((TimeSpan)expiration);
                    }
                    else
                    {
                        options.SetSlidingExpiration((TimeSpan)expiration);
                    }
                }
                else if (expiration is DateTimeOffset)
                {
                    options.SetAbsoluteExpiration((DateTimeOffset)expiration);
                }
                else
                {
                    throw new NotSupportedException("Not support current expiration object settings.");
                }
            }
            return(options);
        }
Exemple #11
0
        public async Task PutAsync <T>(string key, TimeSpan timeout, T value, bool isSlided = false, CancellationToken cancellation = default(CancellationToken))
        {
            CheckIfInitialized();

            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            byte[] blob = null;

            using (var activity = _activitySource?.StartActivity("Put to cache.", ActivityKind.Producer))
            {
                using (var serializerActivity = _activitySource?.StartActivity("Serialize.", ActivityKind.Producer))
                    blob = SerializerFactory.Serialize <T>(value);

                var dceo = new DistributedCacheEntryOptions();
                if (isSlided)
                {
                    dceo.SetSlidingExpiration(timeout);
                }
                else
                {
                    dceo.SetAbsoluteExpiration(timeout);
                }

                activity?.AddTag("cacheKey", key);


                await DistributeCache.SetAsync(key, blob, dceo, cancellation);
            }
        }
Exemple #12
0
        public CacheFactoryResponse <TDeserializedObject> RetrieveOrUpdateRedis <TDeserializedObject>()
        {
            var response = new CacheFactoryResponse <TDeserializedObject>();
            var watch    = Stopwatch.StartNew();

            var valueToReturn = _distributedCache.GetString(_cacheKey);

            if (valueToReturn != null)
            {
                response.DataLoadType = "From Redis";
            }
            else
            {
                valueToReturn = System.IO.File.ReadAllText(_fileName);
                Thread.Sleep(2000);

                var dependency = new DistributedCacheEntryOptions();
                dependency.SetSlidingExpiration(TimeSpan.FromSeconds(10));
                _distributedCache.SetString(_cacheKey, valueToReturn, dependency);

                response.DataLoadType = "From File";
            }
            watch.Stop();

            response.ElapsedMilliseconds       = watch.ElapsedMilliseconds;
            response.CachedJsonContent         = valueToReturn;
            response.DeserializedCachedContent = JsonConvert.DeserializeObject <TDeserializedObject>(valueToReturn);

            return(response);
        }
Exemple #13
0
        public void Save(Request request)
        {
            try
            {
                var cacheData = _cache.Get(request.ClientId.ToString());
                if (cacheData == null)
                {
                    throw new ClientIdNaoExisteException(request.ClientId);
                }

                var jsonStr        = Encoding.UTF8.GetString(cacheData);
                var cachedRequests = JsonConvert.DeserializeObject <List <Request> >(jsonStr);

                cachedRequests.Add(request);
                var options = new DistributedCacheEntryOptions();
                options.SetSlidingExpiration(TimeSpan.FromHours(2));
                _cache.Set(request.ClientId.ToString(), Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(cachedRequests)),
                           options);
            }
            catch (ClientIdNaoExisteException)
            {
                throw;
            }
            catch (Exception exception) {
                _logger.LogCritical(2, exception, "Erro ao salvar novo request no cache");
                throw;
            }
        }
Exemple #14
0
        public void Delete(Guid requestId, Guid clientId)
        {
            try
            {
                var cacheData = _cache.Get(clientId.ToString());
                var requests  = new List <Request>();
                if (cacheData == null)
                {
                    throw new RequestNaoExisteException(requestId);
                }

                var jsonStr = Encoding.UTF8.GetString(cacheData);
                requests = JsonConvert.DeserializeObject <List <Request> >(jsonStr);

                if (!requests.Any(r => r.Id == requestId))
                {
                    throw new RequestNaoExisteException(requestId);
                }

                requests.Remove(requests.Find(r => r.Id == requestId));
                var options = new DistributedCacheEntryOptions();
                options.SetSlidingExpiration(TimeSpan.FromHours(2));
                _cache.Set(clientId.ToString(), Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(requests)),
                           options);
            }
            catch (RequestNaoExisteException)
            {
                throw;
            }
            catch (Exception exception)
            {
                _logger.LogCritical(2, exception, "Erro ao salvar novo request no cache");
                throw;
            }
        }
Exemple #15
0
        private void CreateNewRequestStorage(Guid clientId)
        {
            var options = new DistributedCacheEntryOptions();

            options.SetSlidingExpiration(TimeSpan.FromHours(2));
            _cache.Set(clientId.ToString(), Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(new Request[] {})), options);
        }
        /// <summary>
        /// Sync method to set the cache
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void Put <T>(this IDistributedCache cache, string key, T value, int expirationTime)
        {
            var options = new DistributedCacheEntryOptions();

            options.SetSlidingExpiration(TimeSpan.FromMinutes(10));
            cache.SetString(key, JsonConvert.SerializeObject(value), options);
        }
        /// <summary>
        /// Extension method to set cache
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static async Task PutAsync <T>(this IDistributedCache cache, string key, T value, int expirationTime)
        {
            var options = new DistributedCacheEntryOptions();

            options.SetSlidingExpiration(TimeSpan.FromMinutes(expirationTime));
            await cache.SetStringAsync(key, JsonConvert.SerializeObject(value), options);
        }
Exemple #18
0
        public void Main()
        {
            _cacheEntryOptions = new DistributedCacheEntryOptions();
            _cacheEntryOptions.SetSlidingExpiration(TimeSpan.FromSeconds(10));

            var cache = new SqlServerCache(
                new CacheOptions(
                    new SqlServerCacheOptions()
            {
                ConnectionString = Configuration.Get("ConnectionString"),
                SchemaName       = Configuration.Get("SchemaName"),
                TableName        = Configuration.Get("TableName")
            }));

            cache.Connect();

            SetKey(cache, "0");

            PriodicallyReadKey(cache, TimeSpan.FromSeconds(1));

            PeriodciallyRemoveKey(cache, TimeSpan.FromSeconds(11));

            PeriodciallySetKey(cache, TimeSpan.FromSeconds(13));

            Console.ReadLine();
            Console.WriteLine("Shutting down");
        }
        public async Task <IActionResult> RedisCache()
        {
            IList <Person> data = new List <Person>();

            var isCacheString = _distributedCache.GetString("RedisData");

            if (string.IsNullOrEmpty(isCacheString))
            {
                data = await _context.Person.ToListAsync();

                // convert collection into serialized stringn
                var dataString = JsonConvert.SerializeObject(data);

                var distributedCacheOptions = new DistributedCacheEntryOptions();
                distributedCacheOptions.SetSlidingExpiration(TimeSpan.FromSeconds(5000));

                await _distributedCache.SetStringAsync("RedisData", dataString, distributedCacheOptions);
            }
            else
            {
                data = JsonConvert.DeserializeObject <IList <Person> >(isCacheString);
            }

            return(View(data));
        }
Exemple #20
0
        public IActionResult EmployeeList()
        {
            //Testing of cache...

            //string value = _cache.GetString("CacheTime");

            //if (value == null)
            //{
            //    value = DateTime.Now.ToString();
            //    var options = new DistributedCacheEntryOptions();
            //    options.SetSlidingExpiration(TimeSpan.FromMinutes(1));
            //    _cache.SetString("CacheTime", value, options);
            //}

            //string test1 = value;



            ////////////using (HttpClient client = new HttpClient())
            ////////////{
            ////////////    HttpResponseMessage response = client.GetAsync("http://localhost:8426/api/Employee").Result;
            ////////////    var jsondata = response.Content.ReadAsStringAsync().Result;
            ////////////    EmployeeObject obj = JsonConvert.DeserializeObject<EmployeeObject>(jsondata);
            ////////////    List<EmployeeModel> Employee = new List<EmployeeModel>();
            ////////////    foreach (var test in obj.Employees)
            ////////////    {
            ////////////        Employee.Add(test);
            ////////////    }
            ////////////    return View(Employee);
            ////////////}


            var value = _cache.GetString("EmployeeData");

            if (value != null)
            {
                //var EmployeeCache = JsonConvert.DeserializeObject(value);
                List <EmployeeModel> EmployeeCache = JsonConvert.DeserializeObject <List <EmployeeModel> >(value);

                return(View(EmployeeCache));
            }
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response  = client.GetAsync("http://localhost:8426/api/Employee").Result;
                var                  jsondata = response.Content.ReadAsStringAsync().Result;
                EmployeeObject       obj      = JsonConvert.DeserializeObject <EmployeeObject>(jsondata);
                List <EmployeeModel> Employee = new List <EmployeeModel>();
                foreach (var test in obj.Employees)
                {
                    Employee.Add(test);
                }

                var options = new DistributedCacheEntryOptions();
                options.SetSlidingExpiration(TimeSpan.FromMinutes(1));
                _cache.SetString("EmployeeData", JsonConvert.SerializeObject(Employee), options);

                return(View(Employee));
            }
        }
        public static void Set(string key, byte[] value, int minutes)
        {
            var options = new DistributedCacheEntryOptions();

            options.SetSlidingExpiration(TimeSpan.FromMinutes(minutes));

            Set(key, value, options);
        }
        public static async Task SetAsync(string key, byte[] value, int minutes)
        {
            var options = new DistributedCacheEntryOptions();

            options.SetSlidingExpiration(TimeSpan.FromMinutes(minutes));

            await SetAsync(key, value, options);
        }
        public async Task <JsonResult> SetCacheWithExpiration(string key, string value, int slidingExpirationInSecond, [FromServices] IDistributedCache cache)
        {
            var options = new DistributedCacheEntryOptions();

            options.SetSlidingExpiration(TimeSpan.FromSeconds(slidingExpirationInSecond));
            await cache.SetStringAsync(key, value, options);

            return(new JsonResult(new { key = key, value = value, SlidingExpirationInSecond = slidingExpirationInSecond }));
        }
        private async Task SetCacheAsync(string type, NBaseData.BaseData baseData)
        {
            type = type.ToUpperInvariant();
            var key = $"BaseData.{type}";
            DistributedCacheEntryOptions options = new DistributedCacheEntryOptions();

            options.SetSlidingExpiration(TimeSpan.FromMinutes(30));
            await _cache.SetAsync(key, baseData, options);
        }
Exemple #25
0
        public async Task AddAsync <T>(string key, T t)
        {
            var serializedObject = JsonConvert.SerializeObject(t);
            var encodedObject    = Encoding.UTF8.GetBytes(serializedObject);
            DistributedCacheEntryOptions options = new DistributedCacheEntryOptions();

            options.SetSlidingExpiration(new TimeSpan(0, 1, 0));
            await _cache.SetAsync(key, encodedObject, options);
        }
        public async Task RenewAsync(string key, WeChatSessionInfo sessionInfo, WeChatMiniProgramOptions currentOption)
        {
            await _distributedCache.RemoveAsync(key);

            DistributedCacheEntryOptions options = new DistributedCacheEntryOptions();

            options.SetSlidingExpiration(currentOption.CacheSlidingExpiration);
            await _distributedCache.SetAsync(key, CreateSesionBytes(sessionInfo), options);
        }
        public void ArmazenarValorCacheExpiraInatividade(string chave, string valor)
        {
            DistributedCacheEntryOptions opcoesCache =
                new DistributedCacheEntryOptions();

            //Sliding é para quando ficar inativo por tempo x, o cache expira.
            opcoesCache.SetSlidingExpiration(TimeSpan.FromMinutes(1));

            _distributedCache.SetString(chave, valor, opcoesCache);
        }
Exemple #28
0
 private void GetOptions(ref DistributedCacheEntryOptions options)
 {
     if (!options.AbsoluteExpiration.HasValue &&
         !options.AbsoluteExpirationRelativeToNow.HasValue &&
         !options.SlidingExpiration.HasValue)
     {
         DistributedCacheEntryOptions expr = new DistributedCacheEntryOptions();
         expr.SetSlidingExpiration(_defaultSlidingExpiration);
         options = expr;
     }
 }
        /// <inheritdoc/>
        public async Task AddAsync(string requestUri, AccessTokenResponse accessToken, CancellationToken token)
        {
            ValidateArguments(requestUri, accessToken);

            var cacheKey = CreateCacheKey(requestUri);
            var options  = new DistributedCacheEntryOptions();

            options.SetSlidingExpiration(TimeSpan.FromSeconds(accessToken.ExpiresIn));

            await _distributedCache.SetStringAsync(cacheKey, accessToken.AccessToken, options, token);
        }
Exemple #30
0
        /// <summary>
        /// 设置字符串
        /// </summary>
        /// <param name="distributedCache"></param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="secondTimeout">超时时间 秒</param>
        public static void SetString(this IDistributedCache distributedCache, string key, string value, int secondTimeout)
        {
            DistributedCacheEntryOptions options = new DistributedCacheEntryOptions();

            //设置绝对过期时间 两种写法
            //options.AbsoluteExpiration = DateTime.Now.AddMinutes(30);
            //options.SetAbsoluteExpiration(DateTime.Now.AddMinutes(30));
            //设置滑动过期时间 两种写法
            //options.SlidingExpiration = TimeSpan.FromSeconds(30);
            options.SetSlidingExpiration(TimeSpan.FromSeconds(secondTimeout));
            distributedCache.SetString(key, value, options);
        }