public async Task <IActionResult> Usage() { // 1. insert a new caching item. var obj = new Product() { Id = 100, Name = "Product100" }; var cacheEntry = new CacheEntry("mykey", obj, TimeSpan.FromSeconds(3600)); await _caching.SetAsync(cacheEntry); // 2. get a caching item by specify key. dynamic product = await _caching.GetAsync("mykey"); var id = product.Id; var name = product.Name; // 3. remove caching item. // 3.1 remove caching item by specify key. await _caching.RemoveAsync("mykey"); // 3.2 remove all expirate caching item. await _caching.FlushAllExpirationAsync(); return(Content("ok")); }
/// <summary> /// 请求Api前准备验签内容 /// </summary> /// <returns>返回验签内容</returns> private async Task <BaseAuthInput> BeforeRequestNpsApiAsync() { var cacheValue = await _caching.GetAsync(_npsApi_Auth_CacheKey); if (cacheValue == null) { var serverTime = await _npsApi.ServerTimeAsync(); string timestamp = serverTime?.Timestamp ?? DateTime.Now.ToTimestamp(); string authKey = EncryptHelper.Md5By32($"{_auth_Key}{timestamp}").ToLower(); var baseAuthInput = new BaseAuthInput { AuthKey = authKey, Timestamp = timestamp }; await _caching.SetAsync(_npsApi_Auth_CacheKey, baseAuthInput.ToJson(), TimeSpan.FromSeconds(15)); return(baseAuthInput); } else { return(cacheValue.FromJson <BaseAuthInput>()); } }
/// <summary> /// 有返回值的 异步/同步 方法拦截 /// </summary> /// <param name="invocation">IInvocation</param> /// <param name="proceed">Func<IInvocation, Task></param> protected override async Task <TResult> InterceptAsync <TResult>(IInvocation invocation, Func <IInvocation, Task <TResult> > proceed) { var methodInfo = invocation.MethodInvocationTarget ?? invocation.Method; var cachingAttribute = methodInfo.GetCustomAttributes(typeof(CachingAttribute), false).FirstOrDefault(); if (cachingAttribute is CachingAttribute attribute) { var methodName = $"开启缓存拦截:{methodInfo.Name}()->"; var hashCode = invocation.GetHashCode(); using (_logger.BeginScope("_cache_Result_Intercept:{hashCode}", hashCode)) { try { var cachingKey = CustomCacheKey(invocation); var cacheValue = await _caching.GetAsync(cachingKey); if (cacheValue != null) { return(cacheValue.FromJson <TResult>()); } var result = await proceed(invocation).ConfigureAwait(false); if (cachingKey.IsNotNullOrWhiteSpace()) { var timeSpan = attribute.ExpirationType switch { ExpirationType.Second => TimeSpan.FromSeconds(attribute.AbsoluteExpiration), ExpirationType.Hour => TimeSpan.FromHours(attribute.AbsoluteExpiration), ExpirationType.Day => TimeSpan.FromDays(attribute.AbsoluteExpiration), _ => TimeSpan.FromMinutes(attribute.AbsoluteExpiration), }; await _caching.SetAsync(cachingKey, result.ToJson(), timeSpan); } return(result); } catch (Exception ex) { _logger.LogError($"{methodName}开启缓存出现异常,异常原因:{ex.Message + ex.InnerException}."); throw new NpsException(ex.Message, StatusCode.Error); } } } else { return(await proceed(invocation).ConfigureAwait(false)); } }