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); }
// 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); }
public async Task <IActionResult> Index() { IEnumerable <Movies> movies = null; using (IAsyncCursor <Movies> cursor = await this._dbContext.Movies.FindAsync(new BsonDocument())) { while (await cursor.MoveNextAsync()) { movies = cursor.Current; } } string jsonEmployees = _cache.GetString("Movies"); if (jsonEmployees == null) { IEnumerable <Movies> employees = movies; jsonEmployees = JsonSerializer. Serialize <IEnumerable <Movies> >(employees); var options = new DistributedCacheEntryOptions(); options.SetAbsoluteExpiration(DateTimeOffset.Now.AddMinutes(1)); _cache.SetString("Movies", jsonEmployees, options); } JsonSerializerOptions opt = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }; List <Movies> data = JsonSerializer.Deserialize <List <Movies> >(jsonEmployees, opt); return(View(movies)); }
public IEnumerable <Inventory> GetAll() { try { List <Inventory> inventories; string jsonInventories = redisCache.GetString("reddisCacheInventories"); if (string.IsNullOrEmpty(jsonInventories)) { inventories = _inventoryContext.InventoryMaster.ToList(); jsonInventories = JsonSerializer.Serialize <List <Inventory> >(inventories); var options = new DistributedCacheEntryOptions(); options.SetAbsoluteExpiration(DateTimeOffset.Now.AddMinutes(1)); redisCache.SetString("reddisCacheInventories", jsonInventories, options); } JsonSerializerOptions opt = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }; List <Inventory> data = JsonSerializer.Deserialize <List <Inventory> >(jsonInventories, opt); return(data); } catch (StackExchange.Redis.RedisConnectionException) { return(Enumerable.Empty <Inventory>()); } }
public async Task <IEnumerable <MomoModel> > GetMomo(int id) { var dataCache = await _cache.GetStringAsync(MOMO_KEY); if (string.IsNullOrWhiteSpace(dataCache)) { var momos = GetAllMomos(); await Task.Delay(2000); var momoToJson = JsonConvert.SerializeObject(momos); var cacheSettings = new DistributedCacheEntryOptions(); cacheSettings.SetAbsoluteExpiration(TimeSpan.FromMinutes(2)); await _cache.SetStringAsync(MOMO_KEY, momoToJson, cacheSettings); return(momos); } var momosFromCache = JsonConvert.DeserializeObject <List <MomoModel> >(dataCache); if (id == 4) { return(momosFromCache.Where(x => x.Id == id)); } return(momosFromCache); }
public async Task <IActionResult> GetAsync(int Id) { var key = $"{_envName}:items:{Id}"; var Item = await _cache.GetStringAsync(key); if (Item is null) { var ItemFrmDb = await _dbContext.Items.SingleOrDefaultAsync(c => c.ItemId == Id); if (ItemFrmDb is null) { return(NotFound()); } else { Item = JsonSerializer.Serialize(_mapper.Map <ItemDto>(ItemFrmDb)); var options = new DistributedCacheEntryOptions(); options.SetAbsoluteExpiration(DateTimeOffset.Now.AddMinutes(_cacheExpirationMins)); await _cache.SetStringAsync(key, Item, options); } } var ItemDtoOut = JsonSerializer.Deserialize <ItemDto>(Item); return(Ok(ItemDtoOut)); }
public RedisRepository(IDistributedCache cache, IConfiguration configuration) { _cache = cache; _expirationMinutes = configuration.GetValue <int>("Redis:ExpirationMinutes", 1); _cacheOptions = new DistributedCacheEntryOptions(); _cacheOptions.SetAbsoluteExpiration(TimeSpan.FromMinutes(_expirationMinutes)); }
public ContentResult Get( [FromServices] IConfiguration config, [FromServices] IDistributedCache cache) { string valorJSON = cache.GetString("Cotacoes"); if (valorJSON == null) { using (SqlConnection conexao = new SqlConnection( config.GetConnectionString("BaseCotacoes"))) { valorJSON = conexao.QueryFirst <string>( "SELECT Sigla " + ",NomeMoeda " + ",UltimaCotacao " + ",GETDATE() AS DataProcessamento " + ",ValorComercial AS 'Cotacoes.Comercial' " + ",ValorTurismo AS 'Cotacoes.Turismo' " + "FROM dbo.Cotacoes " + "ORDER BY NomeMoeda " + "FOR JSON PATH, ROOT('Moedas')"); } DistributedCacheEntryOptions opcoesCache = new DistributedCacheEntryOptions(); opcoesCache.SetAbsoluteExpiration( TimeSpan.FromMinutes(2)); cache.SetString("Cotacoes", valorJSON, opcoesCache); } return(Content(valorJSON, "application/json")); }
/// <summary> /// 异步将对象存入缓存中,使用指定时长 /// </summary> public static Task SetAsync(this IDistributedCache cache, string key, object value, int cacheSeconds) { DistributedCacheEntryOptions options = new DistributedCacheEntryOptions(); options.SetAbsoluteExpiration(TimeSpan.FromSeconds(cacheSeconds)); return(cache.SetAsync(key, value, options)); }
public async Task <IActionResult> Get() { var stopwatch = new Stopwatch(); stopwatch.Start(); string valorJSON = _cache.GetString("KeyExample"); if (valorJSON == null) { // Simulando busca informação do banco await Task.Delay(5000); valorJSON = "example"; DistributedCacheEntryOptions opcoesCache = new DistributedCacheEntryOptions(); opcoesCache.SetAbsoluteExpiration( TimeSpan.FromSeconds(30)); _cache.SetString("KeyExample", valorJSON, opcoesCache); } stopwatch.Stop(); return(Ok(new { tempo = stopwatch.ElapsedMilliseconds, valor = valorJSON })); }
public static async Task WriteValueToCache(ILogger logger, IDistributedCache cache, string key, object value, TimeSpan expires) { if (expires == TimeSpan.Zero) { return; } if (value == null) { return; } var options = new DistributedCacheEntryOptions(); options.SetAbsoluteExpiration(expires); logger.LogDebug("WriteValueToCache key {0}", key); try { await cache.SetAsync(key, ObjectToByteArray(value), options).ConfigureAwait(false); logger.LogDebug("WriteValueToCache key {0} complete", key); } catch (Exception ex) { logger.LogWarning(1, ex, $"Failed writing value {key} to cache."); } }
private ObjectToken GenerateToken(IUserAuthenticate user) { ClaimsIdentity identity = new ClaimsIdentity( new[] { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), new Claim("AccessLogged", user.Access), new Claim("UserProfileLogged", user.UserProfile.GetHashCode().ToString()), new Claim("EnterpriseIdLogged", user.EnterpriseId.ToString()) } ); DateTime dataCriacao = DateTime.Now; DateTime dataExpiracao = dataCriacao + TimeSpan.FromSeconds(_tokenConfigurations.Seconds); // Calcula o tempo máximo de validade do refresh token // (o mesmo será invalidado automaticamente pelo Redis) TimeSpan finalExpiration = TimeSpan.FromSeconds(_tokenConfigurations.FinalExpiration); var handler = new JwtSecurityTokenHandler(); var securityToken = handler.CreateToken(new SecurityTokenDescriptor { Issuer = _tokenConfigurations.Issuer, Audience = _tokenConfigurations.Audience, SigningCredentials = _signingConfigurations.SigningCredentials, Subject = identity, NotBefore = dataCriacao, Expires = dataExpiracao }); var token = handler.WriteToken(securityToken); var resultado = new ObjectToken() { authenticated = true, created = dataCriacao.ToString("yyyy-MM-dd HH:mm:ss"), expiration = dataExpiracao.ToString("yyyy-MM-dd HH:mm:ss"), accessToken = token, refreshToken = Guid.NewGuid().ToString().Replace("-", String.Empty), message = "OK" }; // Armazena o refresh token em cache através do Redis var refreshTokenData = new RefreshTokenData(); refreshTokenData.RefreshToken = resultado.refreshToken; refreshTokenData.Access = user.Access; DistributedCacheEntryOptions opcoesCache = new DistributedCacheEntryOptions(); opcoesCache.SetAbsoluteExpiration(finalExpiration); opcoesCache.AbsoluteExpiration = DateTime.Now.Add(finalExpiration); opcoesCache.SlidingExpiration = finalExpiration; _cache.SetString(resultado.refreshToken, JsonConvert.SerializeObject(refreshTokenData), opcoesCache); return(resultado); }
public async void CreateCache(string cacheName, string data, int minutos) { DistributedCacheEntryOptions opcoesCache = new DistributedCacheEntryOptions(); opcoesCache.SetAbsoluteExpiration(TimeSpan.FromMinutes(minutos)); await _cache.SetStringAsync(cacheName, data, opcoesCache); }
private async Task <T> GetFromCacheAndSetAsync <T>(string area, string key, Func <Task <T> > getAsync) { var fullKey = $"{area}-{key}"; var json = await cache.GetStringAsync(fullKey); if (!string.IsNullOrWhiteSpace(json)) { log.LogInformation($"{fullKey} retrieved from cache"); return(JsonConvert.DeserializeObject <T>(json)); } var result = await getAsync(); json = JsonConvert.SerializeObject(result); var cacheOptions = new DistributedCacheEntryOptions(); cacheOptions.SetAbsoluteExpiration(TimeSpan.FromMinutes(cacheTimeoutInMinutes)); await cache.SetStringAsync(fullKey, json, cacheOptions); log.LogInformation($"{fullKey} retrieved from API"); return(result); }
public List <Cookie> GetAllCookies() { List <Cookie> cookies; //if no cache is passed into the constructor //of this service, just get the cookies from the database and return them if (_cache == null) { return(cookies = _context.Cookies.ToList()); } //first, try to get cookies from cache var cachedCookies = _cache.GetString("cookies"); if (!string.IsNullOrEmpty(cachedCookies)) { //if they are there, deserialize them cookies = JsonConvert.DeserializeObject <List <Cookie> >(cachedCookies); } else { //if no cookies in are in cache yet, get them from the database cookies = _context.Cookies.ToList(); DistributedCacheEntryOptions options = new DistributedCacheEntryOptions(); options.SetAbsoluteExpiration(new System.TimeSpan(0, 0, 15)); //and then, put them in cache _cache.SetString("cookies", JsonConvert.SerializeObject(cookies), options); } return(cookies); }
public async Task <ActionResult> Get() { _logger.LogInformation(ConstantVarriables.CourseApiGetAllEnterMessage); ObjectResult response; try { List <ProgramDto> listProgram = new List <ProgramDto>(); //Get data from redis cache var cachedObj = _cache.GetString("ProgramCookies"); if (string.IsNullOrEmpty(cachedObj)) { var data = await _programService.GetAllProgram(); listProgram = _mapper.Map <List <ProgramDto> >(data); //Set data to redis cache var options = new DistributedCacheEntryOptions(); options.SetAbsoluteExpiration(DateTimeOffset.Now.AddMinutes(1)); _cache.SetString("ProgramCookies", JsonConvert.SerializeObject(listProgram), options); } else { listProgram = JsonConvert.DeserializeObject <List <ProgramDto> >(cachedObj); } response = Ok(listProgram); } catch (Exception ex) { _logger.LogError(ex, ex.Message); response = BadRequest(ConstantVarriables.GenericExeptionMessage); } _logger.LogInformation(ConstantVarriables.CourseApiGetAllExitMessage); return(response); }
public async Task <IActionResult> ListarUsuarios() { _requestCount++; Debug.WriteLine($"listar-usuarios, {_requestCount}ª vez"); //if (_requestCount % 6 != 0) { await Task.Delay(3000); //1 Minuto //return StatusCode((int)HttpStatusCode.RequestTimeout, "TimeOut..."); } var cacheKey = "usuarios"; var cacheUsuarios = _distributedCache.GetString(cacheKey); if (!string.IsNullOrEmpty(cacheUsuarios)) { var usuarios = JsonConvert.DeserializeObject <List <Usuario> >(cacheUsuarios); return(Ok(usuarios)); } else { var usuarios = _mapper.Map <List <Usuario> >(_repositorioUsuario.ListarUsuario()); var distributedCacheOption = new DistributedCacheEntryOptions(); distributedCacheOption.SetAbsoluteExpiration(TimeSpan.FromMinutes(_configurationRedis.getConfiguration().tempoCacheMinutos)); _distributedCache.SetString(cacheKey, JsonConvert.SerializeObject(usuarios), distributedCacheOption); return(Ok(usuarios)); } }
private object GenerateToken(string userID, SigningConfigurations signingConfigurations, TokenConfigurations tokenConfigurations, IDistributedCache cache) { ClaimsIdentity identity = new ClaimsIdentity( new GenericIdentity(userID, "Login"), new[] { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), new Claim(JwtRegisteredClaimNames.UniqueName, userID) } ); DateTime dataCriacao = DateTime.Now; DateTime dataExpiracao = dataCriacao + TimeSpan.FromSeconds(tokenConfigurations.Seconds); // Calcula o tempo máximo de validade do refresh token // (o mesmo será invalidado automaticamente pelo Redis) TimeSpan finalExpiration = TimeSpan.FromSeconds(tokenConfigurations.FinalExpiration); var handler = new JwtSecurityTokenHandler(); var securityToken = handler.CreateToken(new SecurityTokenDescriptor { Issuer = tokenConfigurations.Issuer, Audience = tokenConfigurations.Audience, SigningCredentials = signingConfigurations.SigningCredentials, Subject = identity, NotBefore = dataCriacao, Expires = dataExpiracao }); var token = handler.WriteToken(securityToken); var resultado = new { authenticated = true, created = dataCriacao.ToString("yyyy-MM-dd HH:mm:ss"), expiration = dataExpiracao.ToString("yyyy-MM-dd HH:mm:ss"), accessToken = token, refreshToken = Guid.NewGuid().ToString().Replace("-", String.Empty), message = "OK" }; // Armazena o refresh token em cache através do Redis var refreshTokenData = new RefreshTokenData { RefreshToken = resultado.refreshToken, UserID = userID }; DistributedCacheEntryOptions opcoesCache = new DistributedCacheEntryOptions(); opcoesCache.SetAbsoluteExpiration(finalExpiration); cache.SetString(resultado.refreshToken, JsonConvert.SerializeObject(refreshTokenData), opcoesCache); return(resultado); }
public async Task SaveCache(string chave, Object valor, TimeSpan expiracao) { DistributedCacheEntryOptions options = new DistributedCacheEntryOptions(); options.SetAbsoluteExpiration(expiracao); await _repository.SetStringAsync(chave.Trim(), JsonConvert.SerializeObject(valor), options); }
/// <summary> /// 异步获取指定键的缓存项,不存在则从指定委托获取,并回存到缓存中再返回 /// </summary> public static Task <TResult> GetAsync <TResult>(this IDistributedCache cache, string key, Func <Task <TResult> > getAsyncFunc, int cacheSeconds) { DistributedCacheEntryOptions options = new DistributedCacheEntryOptions(); options.SetAbsoluteExpiration(TimeSpan.FromSeconds(cacheSeconds)); return(cache.GetAsync <TResult>(key, getAsyncFunc, options)); }
private static DistributedCacheEntryOptions Create(int expirationTimeInMinutes) { var opcoes = new DistributedCacheEntryOptions(); opcoes.SetAbsoluteExpiration(TimeSpan.FromMinutes(expirationTimeInMinutes)); return(opcoes); }
public ActionResult Criar() { if (ModelState.IsValid) { var cacheKey = "areas"; var cacheAreas = _distributedCache.GetString(cacheKey); var areas = _mapper.Map <List <AreaViewModel> >(_areaRepository.ListarTodos().ToList()); if (!string.IsNullOrEmpty(cacheAreas)) { areas = JsonConvert.DeserializeObject <List <AreaViewModel> >(cacheAreas); } var novaArea = new AreaViewModel() { IdArea = areas.Max(x => x.IdArea) + 1, Descricao = "area " + (areas.Max(x => x.IdArea) + 1), Status = ViewModel.Enum.StatusViewModel.statusAtual.ATIVADO }; areas.Add(novaArea); var distributedCacheOption = new DistributedCacheEntryOptions(); distributedCacheOption.SetAbsoluteExpiration(TimeSpan.FromMinutes(_configurationRedis.getConfiguration().tempoCacheMinutos)); _distributedCache.SetString(cacheKey, JsonConvert.SerializeObject(areas), distributedCacheOption); Console.WriteLine("Adicionado nova area"); return(Ok()); } Console.WriteLine("Erro ao adicionar area"); return(BadRequest(ModelState)); }
public async Task <IActionResult> GetAsync() { var key = $"{_envName}:items"; var Items = await _cache.GetStringAsync(key); if (Items == null) { var ItemsFrmDb = await _dbContext.Items .OrderByDescending(c => c.DateAdded) .ToListAsync(); if (ItemsFrmDb is null) { return(NotFound()); } else { Items = JsonSerializer.Serialize(_mapper.Map <List <ItemDto> >(ItemsFrmDb)); var options = new DistributedCacheEntryOptions(); options.SetAbsoluteExpiration(DateTimeOffset.Now.AddMinutes(_cacheExpirationMins)); await _cache.SetStringAsync(key, Items, options); } } var ItemsOutDto = JsonSerializer.Deserialize <List <ItemDto> >(Items); return(Ok(ItemsOutDto)); }
public async Task <CourseDetailViewModel> GetCourseAsync(int id) { string key = $"Course{id}"; //Proviamo a recuperare l'oggetto dalla cache string serializedObject = await distributedCache.GetStringAsync(key); //Se l'oggetto esisteva in cache (cioè se è diverso da null) if (serializedObject != null) { //Allora lo deserializzo e lo restituisco return(Deserialize <CourseDetailViewModel>(serializedObject)); } //Se invece non esisteva, lo andiamo a recuperare dal database CourseDetailViewModel course = await courseService.GetCourseAsync(id); //Prima di restituire l'oggetto al chiamante, lo serializziamo. //Cioè ne creiamo una rappresentazione stringa o binaria serializedObject = Serialize(course); //Impostiamo la durata di permanenza in cache var cacheOptions = new DistributedCacheEntryOptions(); cacheOptions.SetAbsoluteExpiration(TimeSpan.FromSeconds(60)); //Aggiungiamo in cache l'oggetto serializzato await distributedCache.SetStringAsync(key, serializedObject, cacheOptions); //Lo restituisco return(course); }
public UpdateController(IUpdateService updateService, IDistributedCache cache) { _updateService = updateService; _cache = cache; _cacheSetting = new DistributedCacheEntryOptions(); _cacheSetting.SetAbsoluteExpiration(TimeSpan.FromSeconds(30)); }
public async Task <T> GetOrCreate(string key, Func <T> createItem) { T cacheEntry; string cachedResult = await _cache.GetStringAsync(key); if (cachedResult is null) { // Key not in cache, so create data cacheEntry = createItem(); TimeSpan parseConfigResult; var isParseSuccess = TimeSpan.TryParse(_config.GetValue <string>("CacheExpirationTimespan"), out parseConfigResult); var expirationTime = isParseSuccess ? parseConfigResult : new TimeSpan(0, 60, 0); var cacheEntryOptions = new DistributedCacheEntryOptions(); cacheEntryOptions.SetAbsoluteExpiration(expirationTime); // Save data in cache. _cache.SetString(key, JsonConvert.SerializeObject(cacheEntry), cacheEntryOptions); return(cacheEntry); } else { return(JsonConvert.DeserializeObject <T>(cachedResult)); } }
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); } }
/// <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)); }
protected async Task ArmazenarCacheRedis(string chave, string valor) { DistributedCacheEntryOptions opcoesCache = new DistributedCacheEntryOptions(); opcoesCache.SetAbsoluteExpiration(TimeSpan.FromSeconds(30)); await _cache.SetStringAsync(chave, valor, opcoesCache); }
public async Task <IEnumerable <RoomResource> > Get(int hotelId, CancellationToken token) { var key = $"_rooms_for_hotel_{hotelId}"; var rooms = this.cache.GetString(key); if (!string.IsNullOrEmpty(rooms)) { this.logger.LogInfo("DistributedCachedRoomsController-Get(hotelId) cache hit"); var roomsList = Deserialize <List <RoomResource> >(rooms); return(roomsList); } else { this.logger.LogInfo("DistributedCachedRoomsController-Get(hotelId) db hit"); var roomsEntities = await this.context.Rooms .Include(h => h.Hotel) .Where(h => h.Hotel.Id == hotelId) .ToListAsync(token); var options = new DistributedCacheEntryOptions(); options.SetAbsoluteExpiration(TimeSpan.FromSeconds(3)); var resources = roomsEntities.Select(e => e.MapAsResource()); this.cache.SetString(key, Serialize(resources), options); return(resources); } }