public void Set_And_Remove_Should_Succeed() { var cacheKey = $"{_namespace}_{Guid.NewGuid().ToString()}"; hybridCaching_1.Set(cacheKey, "val", TimeSpan.FromSeconds(30)); hybridCaching_1.Remove(cacheKey); var res = hybridCaching_1.Exists(cacheKey); Assert.False(res); }
public string Get(string str) { var method = str.ToLower(); switch (method) { case "get": { var res = _provider.Get <string>("demo"); return($"cached value : {res}"); } case "getset": { var res = _provider.Get("demo", () => "1-456", TimeSpan.FromHours(1)); return($"cached value : {res}"); } case "set": _provider.Set("demo", "1-123", TimeSpan.FromHours(1)); return("seted"); case "remove": _provider.Remove("demo"); return("removed"); default: return("default"); } }
/// <summary> /// Processes the evict. /// </summary> /// <param name="invocation">Invocation.</param> /// <param name="isBefore">If set to <c>true</c> is before.</param> private void ProcessEvict(IInvocation invocation, bool isBefore) { var serviceMethod = invocation.Method ?? invocation.MethodInvocationTarget; if (GetMethodAttributes(serviceMethod).FirstOrDefault(x => typeof(EasyCachingEvictAttribute).IsAssignableFrom(x.GetType())) is EasyCachingEvictAttribute attribute && attribute.IsBefore == isBefore) { try { if (attribute.IsAll) { //If is all , clear all cached items which cachekey start with the prefix. var cacheKeyPrefix = _keyGenerator.GetCacheKeyPrefix(serviceMethod, attribute.CacheKeyPrefix); if (attribute.IsHybridProvider) { _hybridCachingProvider.RemoveByPrefix(cacheKeyPrefix); } else { var _cacheProvider = _cacheProviderFactory.GetCachingProvider(attribute.CacheProviderName ?? _options.Value.CacheProviderName); _cacheProvider.RemoveByPrefix(cacheKeyPrefix); } } else { //If not all , just remove the cached item by its cachekey. var cacheKey = string.IsNullOrEmpty(attribute.CacheKey) ? _keyGenerator.GetCacheKey(serviceMethod, invocation.Arguments, attribute.CacheKeyPrefix) : attribute.CacheKey ; if (attribute.IsHybridProvider) { _hybridCachingProvider.Remove(cacheKey); } else { var _cacheProvider = _cacheProviderFactory.GetCachingProvider(attribute.CacheProviderName ?? _options.Value.CacheProviderName); _cacheProvider.Remove(cacheKey); } } } catch (Exception ex) { if (!attribute.IsHighAvailability) { throw; } else { _logger?.LogError(new EventId(), ex, $"Cache provider remove error."); } } } }
public void Remove(string key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } _expirations.TryRemove(key, out TimeSpan _); _hybridCachingProvider.Remove(key); }
public string Get(int type = 1) { if (type == 1) { _provider.Remove("demo"); return("removed"); } else if (type == 2) { _provider.Set("demo", "123", TimeSpan.FromMinutes(1)); return("seted"); } else if (type == 3) { var res = _provider.Get("demo", () => "456", TimeSpan.FromMinutes(1)); return($"cached value : {res}"); } else { return("error"); } }
public async Task Invoke(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var endpoint = context.GetEndpoint(); if (endpoint == null) { await _next(context); return; } var requiredValues = ((RouteEndpoint)endpoint).RoutePattern.RequiredValues; if (requiredValues.Count() == 0) { await _next(context); return; } var controller = requiredValues["controller"]?.ToString(); var action = requiredValues["action"]?.ToString(); if (string.IsNullOrEmpty(controller)) { await _next(context); return; } string tokenTxt = string.Empty; string refreshTokenTxt = string.Empty; //读取Request //context.Request.EnableBuffering(); //var requestReader = new StreamReader(context.Request.Body); //var requestContent = requestReader.ReadToEnd(); //context.Request.Body.Position = 0; // Allow Anonymous skips all authorization if (endpoint?.Metadata.GetMetadata <IAllowAnonymous>() != null) { //如果是调用登陆API并且调用成功,需要保存accesstoken道cache if (string.Equals(controller, "account", StringComparison.InvariantCultureIgnoreCase) && (string.Equals(action, "login", StringComparison.InvariantCultureIgnoreCase) || string.Equals(action, "refreshaccesstoken", StringComparison.InvariantCultureIgnoreCase)) ) { string responseContent; var originalBodyStream = context.Response.Body; using (var fakeResponseBody = new MemoryStream()) { context.Response.Body = fakeResponseBody; await _next(context); fakeResponseBody.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(fakeResponseBody)) { responseContent = await reader.ReadToEndAsync(); fakeResponseBody.Seek(0, SeekOrigin.Begin); await fakeResponseBody.CopyToAsync(originalBodyStream); } } if (context.Response.StatusCode == 200) { tokenTxt = JObject.Parse(responseContent).GetValue("token").ToString(); refreshTokenTxt = JObject.Parse(responseContent).GetValue("refreshToken").ToString(); var claimsInfo = GetClaimsInfo(tokenTxt); if (!string.IsNullOrEmpty(claimsInfo.Account)) { var key = $"{tokenPrefx}:{claimsInfo.Account}:{claimsInfo.Id}"; //_cache.SetString(key, claimsInfo.Token, new DistributedCacheEntryOptions { AbsoluteExpiration = claimsInfo.Expire }); _cache.Set(key, claimsInfo.Token, claimsInfo.Expire - DateTime.Now); var refreshTokenKey = $"{refreshTokenPrefx}:{claimsInfo.Account}:{claimsInfo.Id}"; //_cache.SetString(refreshTokenKey, refreshTokenTxt, new DistributedCacheEntryOptions { AbsoluteExpiration = DateTime.Now.AddMinutes(_jwtConfig.RefreshTokenExpire) }); _cache.Set(refreshTokenKey, refreshTokenTxt, TimeSpan.FromSeconds(_jwtConfig.RefreshTokenExpire)); } } } return; } tokenTxt = await context.GetTokenAsync("access_token"); //如果是调用注销API并且调用成功,需要从cahce移除accesstoken if (string.Equals(controller, "account", StringComparison.InvariantCultureIgnoreCase) && string.Equals(action, "logout", StringComparison.InvariantCultureIgnoreCase)) { await _next(context); if (context.Response.StatusCode == 200) { var claimsInfo = GetClaimsInfo(tokenTxt); if (!string.IsNullOrEmpty(claimsInfo.Account)) { var key = $"{tokenPrefx}:{claimsInfo.Account}:{claimsInfo.Id}"; var refreshTokenKey = $"{refreshTokenPrefx}:{claimsInfo.Account}:{claimsInfo.Id}"; //可以考虑事务操作,以后再优化 _cache.Remove(key); _cache.Remove(refreshTokenKey); } } return; } //如果是其他需要授权的API并且调用成功,需要从检查accesstoken是否在缓存中。 if (context.Response.StatusCode == 200) { var claimsInfo = GetClaimsInfo(tokenTxt); if (!string.IsNullOrEmpty(claimsInfo.Account)) { var key = $"{tokenPrefx}:{claimsInfo.Account}:{claimsInfo.Id}"; //var cahceToken = _cache.GetString(key); var cahceToken = _cache.Get <string>(key).Value; if (cahceToken != claimsInfo.Token) { await context.ForbidAsync(); } else { await _next(context); } } return; } }