private async Task InternalInterceptAsynchronous(IInvocation invocation, CachingInterceptorAttribute attribute) { if (attribute is CachingAbleAttribute ableAttribute) { invocation.Proceed(); var task = (Task)invocation.ReturnValue; await task; return; } if (attribute is CachingEvictAttribute evictAttribute) { var(cacheKeys, expireDt) = ProcessEvictBefore(invocation, evictAttribute); var cancelTokenSource = new CancellationTokenSource(); var timeoutPolicy = Policy.TimeoutAsync(_cacheProvider.CacheOptions.PollyTimeoutSeconds, Polly.Timeout.TimeoutStrategy.Optimistic); try { await timeoutPolicy.ExecuteAsync(async (cancellToken) => { invocation.Proceed(); var task = (Task)invocation.ReturnValue; await task; cancellToken.ThrowIfCancellationRequested(); }, cancelTokenSource.Token); _cacheProvider.RemoveAll(cacheKeys); } catch (Exception ex) { LocalVariables.Instance.Queue.Enqueue(new LocalVariables.Model(cacheKeys, expireDt)); if (!attribute.IsHighAvailability) { throw; } else { _logger?.LogError(new EventId(), ex, $"Cache provider remove error."); } } } }
private void InternalInterceptSynchronous(IInvocation invocation, CachingInterceptorAttribute attribute) { var methodInfo = invocation.Method ?? invocation.MethodInvocationTarget; if (attribute is CachingAbleAttribute ableAttribute) { var cacheKey = string.IsNullOrEmpty(attribute.CacheKey) ? _keyGenerator.GetCacheKey(methodInfo, invocation.Arguments, attribute.CacheKeyPrefix) : attribute.CacheKey ; try { var cacheValue = _cacheProvider.GetAsync(cacheKey, methodInfo.ReturnType).GetAwaiter().GetResult(); if (cacheKey != null) { invocation.ReturnValue = cacheValue; } else { invocation.Proceed(); if (!string.IsNullOrWhiteSpace(cacheKey) && invocation.ReturnValue != null) { _cacheProvider.Set(cacheKey, invocation.ReturnValue, TimeSpan.FromSeconds(ableAttribute.Expiration)); } } } catch (Exception ex) { if (!attribute.IsHighAvailability) { throw; } else { _logger?.LogError(new EventId(), ex, $"Cache provider get error."); } } return; } if (attribute is CachingEvictAttribute evictAttribute) { var(cacheKeys, expireDt) = ProcessEvictBefore(invocation, evictAttribute); var cancelTokenSource = new CancellationTokenSource(); var timeoutPolicy = Policy.Timeout(_cacheProvider.CacheOptions.PollyTimeoutSeconds, Polly.Timeout.TimeoutStrategy.Optimistic); try { timeoutPolicy.Execute((cancellToken) => { invocation.Proceed(); cancellToken.ThrowIfCancellationRequested(); }, cancelTokenSource.Token); _cacheProvider.RemoveAll(cacheKeys); } catch (Exception ex) { LocalVariables.Instance.Queue.Enqueue(new LocalVariables.Model(cacheKeys, expireDt)); if (!attribute.IsHighAvailability) { throw; } else { _logger?.LogError(new EventId(), ex, $"Cache provider remove error."); } } } }