public async Task GetAsync_should_return_false_on_unknown_key() { Mock <IDistributedCache> mockDistributedCache = new Mock <IDistributedCache>(); string key = "anything"; var cachedValue = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()); mockDistributedCache.Setup(idc => idc.GetAsync(It.Is <string>(k => k == key) #if NETCOREAPP2_0 , It.IsAny <CancellationToken>() #endif )).Returns(Task.FromResult(cachedValue)); mockDistributedCache.Setup(idc => idc.GetAsync(It.Is <string>(k => k != key) #if NETCOREAPP2_0 , It.IsAny <CancellationToken>() #endif )).Returns(Task.FromResult <byte[]>(null)).Verifiable(); IAsyncCacheProvider <byte[]> provider = mockDistributedCache.Object.AsAsyncCacheProvider <byte[]>(); string someOtherKey = Guid.NewGuid().ToString(); (bool got, byte[] fromCache) = await provider.TryGetAsync(someOtherKey, CancellationToken.None, false); got.Should().BeFalse(); mockDistributedCache.Verify(v => v.GetAsync(someOtherKey #if NETCOREAPP2_0 , It.IsAny <CancellationToken>() #endif ), Times.Once); fromCache.Should().BeNull(); }
public async Task PutAsync_should_put_item_using_passed_nonsliding_ttl() { Mock <IDistributedCache> mockDistributedCache = new Mock <IDistributedCache>(); string key = "anything"; var valueToCache = "something to cache"; IAsyncCacheProvider <string> provider = mockDistributedCache.Object.AsAsyncCacheProvider <string>(); mockDistributedCache.Setup(idc => idc.SetAsync(It.Is <string>(k => k == key), It.IsAny <byte[]>(), It.IsAny <DistributedCacheEntryOptions>() #if !NETCOREAPP1_1 , It.IsAny <CancellationToken>() #endif )).Returns(Task.CompletedTask).Verifiable(); // Because SetStringAsync() is an extension method, we cannot mock it. We mock SetAsync() instead. TimeSpan timespan = TimeSpan.FromSeconds(10); Ttl ttl = new Ttl(timespan, false); await provider.PutAsync(key, valueToCache, ttl, CancellationToken.None, false); mockDistributedCache.Verify(idc => idc.SetAsync(key, It.IsAny <byte[]>(), It.Is <DistributedCacheEntryOptions>(o => o.AbsoluteExpirationRelativeToNow == timespan) #if !NETCOREAPP1_1 , It.IsAny <CancellationToken>() #endif )); }
public async Task PutAsync_should_put_item_using_passed_nonsliding_ttl() { Mock <IDistributedCache> mockDistributedCache = new Mock <IDistributedCache>(); string key = "anything"; var valueToCache = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()); IAsyncCacheProvider <byte[]> provider = mockDistributedCache.Object.AsAsyncCacheProvider <byte[]>(); mockDistributedCache.Setup(idc => idc.SetAsync(It.Is <string>(k => k == key), It.Is <byte[]>(v => v == valueToCache), It.IsAny <DistributedCacheEntryOptions>() #if NETCOREAPP2_0 , It.IsAny <CancellationToken>() #endif )).Returns(Task.CompletedTask).Verifiable(); TimeSpan timespan = TimeSpan.FromSeconds(10); Ttl ttl = new Ttl(timespan, false); await provider.PutAsync(key, valueToCache, ttl, CancellationToken.None, false); mockDistributedCache.Verify(idc => idc.SetAsync(key, valueToCache, It.Is <DistributedCacheEntryOptions>(o => o.AbsoluteExpirationRelativeToNow == timespan) #if NETCOREAPP2_0 , It.IsAny <CancellationToken>() #endif )); }
public CacheManagement(ILogger logger, IPolicyRegistry <string> registry, IAsyncCacheProvider cacheProvider, IMemoryCacheExtended cache) { this.logger = logger; this.registry = registry; this.cacheProvider = cacheProvider.AsyncFor <CacheFormat>(); this.cache = cache; }
public void Should_throw_when_cache_provider_is_null() { IAsyncCacheProvider cacheProvider = null; Action action = () => Policy.CacheAsync(cacheProvider, TimeSpan.MaxValue); action.ShouldThrow <ArgumentNullException>().And.ParamName.Should().Be("cacheProvider"); }
public AsyncCachedEntityReader( IMetadataProvider metadataProvider, IAsyncDatabase database, IAsyncCacheProvider cacheProvider) : base(metadataProvider, database) { Cache = cacheProvider; }
/// <summary> /// <para>Builds a <see cref="Policy"/> that will function like a result cache for delegate executions returning a <typeparamref name="TResult"/>.</para> /// <para>Before executing a delegate, checks whether the <paramref name="cacheProvider"/> holds a value for the cache key specified by <see cref="M:Context.ExecutionKey"/>. /// If the <paramref name="cacheProvider"/> provides a value, returns that value and does not execute the governed delegate. If the <paramref name="cacheProvider"/> does not provide a value, executes the governed delegate, stores the value with the <paramref name="cacheProvider"/>, then returns the value. /// </para> /// </summary> /// <param name="cacheProvider">The cache provider.</param> /// <param name="ttlStrategy">A strategy for specifying ttl for values to be cached.</param> /// <param name="onCacheError">Delegate to call if an exception is thrown when attempting to get a value from or put a value into the cache, passing the execution context, the cache key, and the exception.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">cacheProvider</exception> /// <exception cref="ArgumentNullException">ttlStrategy</exception> public static CachePolicy <TResult> CacheAsync <TResult>(IAsyncCacheProvider cacheProvider, ITtlStrategy ttlStrategy, Action <Context, string, Exception> onCacheError = null) { if (cacheProvider == null) { throw new ArgumentNullException(nameof(cacheProvider)); } return(CacheAsync <TResult>(cacheProvider.AsyncFor <TResult>(), ttlStrategy, DefaultCacheKeyStrategy.Instance.GetCacheKey, onCacheError)); }
/// <summary> /// <para>Builds a <see cref="Policy" /> that will function like a result cache for delegate executions returning a <typeparamref name="TResult"/>.</para> /// <para>Before executing a delegate, checks whether the <paramref name="cacheProvider" /> holds a value for the cache key determined by applying the <paramref name="cacheKeyStrategy"/> to the execution <see cref="Context"/>. /// If the <paramref name="cacheProvider" /> provides a value, returns that value and does not execute the governed delegate. If the <paramref name="cacheProvider" /> does not provide a value, executes the governed delegate, stores the value with the <paramref name="cacheProvider" />, then returns the value. /// </para> /// </summary> /// <param name="cacheProvider">The cache provider.</param> /// <param name="ttl">Duration (ttl) for which to cache values.</param> /// <param name="cacheKeyStrategy">The cache key strategy.</param> /// <param name="onCacheError">Delegate to call if an exception is thrown when attempting to get a value from or put a value into the cache, passing the execution context, the cache key, and the exception.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">cacheKeyStrategy</exception> /// <exception cref="ArgumentNullException">cacheProvider</exception> public static CachePolicy <TResult> CacheAsync <TResult>(IAsyncCacheProvider cacheProvider, TimeSpan ttl, Func <Context, string> cacheKeyStrategy, Action <Context, string, Exception> onCacheError = null) { if (cacheProvider == null) { throw new ArgumentNullException(nameof(cacheProvider)); } return(CacheAsync <TResult>(cacheProvider.AsyncFor <TResult>(), new RelativeTtl(ttl), cacheKeyStrategy, onCacheError)); }
/// <summary> /// <para>Builds an <see cref="AsyncPolicy" /> that will function like a result cache for delegate executions returning a result.</para> /// <para>Before executing a delegate returning a result, checks whether the <paramref name="cacheProvider" /> holds a value for the cache key. /// If the <paramref name="cacheProvider" /> provides a value, returns that value and does not execute the governed delegate. If the <paramref name="cacheProvider" /> does not provide a value, executes the governed delegate, stores the value with the <paramref name="cacheProvider" />, then returns the value. /// </para> /// </summary> /// <param name="cacheProvider">The cache provider.</param> /// <param name="ttlStrategy">A strategy for specifying ttl for values to be cached.</param> /// <param name="onCacheGet">Delegate to call on a cache hit, when value is returned from cache.</param> /// <param name="onCacheMiss">Delegate to call on a cache miss.</param> /// <param name="onCachePut">Delegate to call on cache put.</param> /// <param name="onCacheGetError">Delegate to call if an exception is thrown when attempting to get a value from the cache, passing the execution context, the cache key, and the exception.</param> /// <param name="onCachePutError">Delegate to call if an exception is thrown when attempting to put a value in the cache, passing the execution context, the cache key, and the exception.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">cacheProvider</exception> /// <exception cref="ArgumentNullException">ttlStrategy</exception> /// <exception cref="ArgumentNullException">onCacheGet</exception> /// <exception cref="ArgumentNullException">onCacheMiss</exception> /// <exception cref="ArgumentNullException">onCachePut</exception> /// <exception cref="ArgumentNullException">onCacheGetError</exception> /// <exception cref="ArgumentNullException">onCachePutError</exception> public static AsyncCachePolicy CacheAsync( IAsyncCacheProvider cacheProvider, ITtlStrategy ttlStrategy, Action <Context, string> onCacheGet, Action <Context, string> onCacheMiss, Action <Context, string> onCachePut, Action <Context, string, Exception> onCacheGetError, Action <Context, string, Exception> onCachePutError) => CacheAsync(cacheProvider, ttlStrategy, DefaultCacheKeyStrategy.Instance.GetCacheKey, onCacheGet, onCacheMiss, onCachePut, onCacheGetError, onCachePutError);
/// <summary> /// <para>Builds an <see cref="AsyncPolicy" /> that will function like a result cache for delegate executions returning a result.</para> /// <para>Before executing a delegate returning a result, checks whether the <paramref name="cacheProvider" /> holds a value for the cache key. /// If the <paramref name="cacheProvider" /> provides a value, returns that value and does not execute the governed delegate. If the <paramref name="cacheProvider" /> does not provide a value, executes the governed delegate, stores the value with the <paramref name="cacheProvider" />, then returns the value. /// </para> /// </summary> /// <param name="cacheProvider">The cache provider.</param> /// <param name="ttl">Duration (ttl) for which to cache values.</param> /// <param name="onCacheGet">Delegate to call on a cache hit, when value is returned from cache.</param> /// <param name="onCacheMiss">Delegate to call on a cache miss.</param> /// <param name="onCachePut">Delegate to call on cache put.</param> /// <param name="onCacheGetError">Delegate to call if an exception is thrown when attempting to get a value from the cache, passing the execution context, the cache key, and the exception.</param> /// <param name="onCachePutError">Delegate to call if an exception is thrown when attempting to put a value in the cache, passing the execution context, the cache key, and the exception.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">cacheProvider</exception> /// <exception cref="ArgumentNullException">onCacheGet</exception> /// <exception cref="ArgumentNullException">onCacheMiss</exception> /// <exception cref="ArgumentNullException">onCachePut</exception> /// <exception cref="ArgumentNullException">onCacheGetError</exception> /// <exception cref="ArgumentNullException">onCachePutError</exception> public static AsyncCachePolicy CacheAsync( IAsyncCacheProvider cacheProvider, TimeSpan ttl, Action <Context, string> onCacheGet, Action <Context, string> onCacheMiss, Action <Context, string> onCachePut, Action <Context, string, Exception> onCacheGetError, Action <Context, string, Exception> onCachePutError) => CacheAsync(cacheProvider, new RelativeTtl(ttl), DefaultCacheKeyStrategy.Instance.GetCacheKey, onCacheGet, onCacheMiss, onCachePut, onCacheGetError, onCachePutError);
internal GenericCacheProviderAsync(IAsyncCacheProvider nonGenericCacheProvider) { if (nonGenericCacheProvider == null) { throw new ArgumentNullException(nameof(nonGenericCacheProvider)); } _wrappedCacheProvider = nonGenericCacheProvider; }
public void GetAsync_should_throw_for_cancellation() { Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache> mockDistributedCache = new Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache>(); string key = "anything"; IAsyncCacheProvider <string> provider = mockDistributedCache.Object.AsAsyncCacheProvider <string>(); Func <Task> action = () => provider.GetAsync(key, new CancellationToken(true), false); action.ShouldThrow <OperationCanceledException>(); }
public void GetAsync_should_throw_for_cancellation() { Mock <IDistributedCache> mockDistributedCache = new Mock <IDistributedCache>(); string key = "anything"; IAsyncCacheProvider <byte[]> provider = mockDistributedCache.Object.AsAsyncCacheProvider <byte[]>(); Func <Task> action = () => provider.TryGetAsync(key, new CancellationToken(true), false); action.Should().Throw <OperationCanceledException>(); }
public DefaultPolicy(PollyOptions options, IOptionsMonitor <PollyOptions> configurationChange, ILogger <HttpClient> logger, IAsyncCacheProvider <string> cacheProvider, IPolicyRegistry <string> policyRegistry) { configurationChange.OnChange(ConfigurationChange_ConfigurationChanged); _options = options; _logger = logger; _cacheProvider = cacheProvider.WithSerializer(new HttpResponseCacheSerializer()); _policyRegistry = policyRegistry; }
/// <summary> /// <para>Builds a <see cref="Policy" /> that will function like a result cache for delegate executions returning a result.</para> /// <para>Before executing a delegate returning a result, checks whether the <paramref name="cacheProvider" /> holds a value for the cache key determined by applying the <paramref name="cacheKeyStrategy"/> to the execution <see cref="Context"/>. /// If the <paramref name="cacheProvider" /> provides a value, returns that value and does not execute the governed delegate. If the <paramref name="cacheProvider" /> does not provide a value, executes the governed delegate, stores the value with the <paramref name="cacheProvider" />, then returns the value. /// </para> /// </summary> /// <param name="cacheProvider">The cache provider.</param> /// <param name="ttl">Duration (ttl) for which to cache values.</param> /// <param name="cacheKeyStrategy">The cache key strategy.</param> /// <param name="onCacheGet">Delegate to call on a cache hit, when value is returned from cache.</param> /// <param name="onCacheMiss">Delegate to call on a cache miss.</param> /// <param name="onCachePut">Delegate to call on cache put.</param> /// <param name="onCacheGetError">Delegate to call if an exception is thrown when attempting to get a value from the cache, passing the execution context, the cache key, and the exception.</param> /// <param name="onCachePutError">Delegate to call if an exception is thrown when attempting to put a value in the cache, passing the execution context, the cache key, and the exception.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">cacheProvider</exception> /// <exception cref="ArgumentNullException">cacheKeyStrategy</exception> /// <exception cref="ArgumentNullException">onCacheGet</exception> /// <exception cref="ArgumentNullException">onCacheMiss</exception> /// <exception cref="ArgumentNullException">onCachePut</exception> /// <exception cref="ArgumentNullException">onCacheGetError</exception> /// <exception cref="ArgumentNullException">onCachePutError</exception> public static CachePolicy CacheAsync( IAsyncCacheProvider cacheProvider, TimeSpan ttl, Func <Context, string> cacheKeyStrategy, Action <Context, string> onCacheGet, Action <Context, string> onCacheMiss, Action <Context, string> onCachePut, Action <Context, string, Exception> onCacheGetError, Action <Context, string, Exception> onCachePutError) { return(CacheAsync(cacheProvider, new RelativeTtl(ttl), cacheKeyStrategy, onCacheGet, onCacheMiss, onCachePut, onCacheGetError, onCachePutError)); }
/// <summary> /// <para>Builds a <see cref="Policy" /> that will function like a result cache for delegate executions returning a result.</para> /// <para>Before executing a delegate returning a result, checks whether the <paramref name="cacheProvider" /> holds a value for the cache key determined by applying the <paramref name="cacheKeyStrategy"/> to the execution <see cref="Context"/>. /// If the <paramref name="cacheProvider" /> provides a value, returns that value and does not execute the governed delegate. If the <paramref name="cacheProvider" /> does not provide a value, executes the governed delegate, stores the value with the <paramref name="cacheProvider" />, then returns the value. /// </para> /// </summary> /// <param name="cacheProvider">The cache provider.</param> /// <param name="ttlStrategy">A strategy for specifying ttl for values to be cached.</param> /// <param name="cacheKeyStrategy">The cache key strategy.</param> /// <param name="onCacheGet">Delegate to call on a cache hit, when value is returned from cache.</param> /// <param name="onCacheMiss">Delegate to call on a cache miss.</param> /// <param name="onCachePut">Delegate to call on cache put.</param> /// <param name="onCacheGetError">Delegate to call if an exception is thrown when attempting to get a value from the cache, passing the execution context, the cache key, and the exception.</param> /// <param name="onCachePutError">Delegate to call if an exception is thrown when attempting to put a value in the cache, passing the execution context, the cache key, and the exception.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">cacheProvider</exception> /// <exception cref="ArgumentNullException">ttlStrategy</exception> /// <exception cref="ArgumentNullException">cacheKeyStrategy</exception> /// <exception cref="ArgumentNullException">onCacheGet</exception> /// <exception cref="ArgumentNullException">onCacheMiss</exception> /// <exception cref="ArgumentNullException">onCachePut</exception> /// <exception cref="ArgumentNullException">onCacheGetError</exception> /// <exception cref="ArgumentNullException">onCachePutError</exception> public static CachePolicy CacheAsync( IAsyncCacheProvider cacheProvider, ITtlStrategy ttlStrategy, ICacheKeyStrategy cacheKeyStrategy, Action <Context, string> onCacheGet, Action <Context, string> onCacheMiss, Action <Context, string> onCachePut, Action <Context, string, Exception> onCacheGetError, Action <Context, string, Exception> onCachePutError) { return(CacheAsync(cacheProvider, ttlStrategy, cacheKeyStrategy.GetCacheKey, onCacheGet, onCacheMiss, onCachePut, onCacheGetError, onCachePutError)); }
public async Task GetAsync_should_return_instance_previously_stored_in_cache() { Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache> mockDistributedCache = new Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache>(); string key = "anything"; mockDistributedCache.Setup(idc => idc.GetAsync(It.Is <string>(k => k == key))).Returns(Task.FromResult(new byte[0] { })).Verifiable(); // Because GetStringAsync() is an extension method, we cannot mock it. We mock GetAsync() instead. IAsyncCacheProvider <string> provider = mockDistributedCache.Object.AsAsyncCacheProvider <string>(); string got = await provider.GetAsync(key, CancellationToken.None, false); mockDistributedCache.Verify(v => v.GetAsync(key), Times.Once); }
public void PutAsync_should_throw_for_cancellation() { Mock <IDistributedCache> mockDistributedCache = new Mock <IDistributedCache>(); string key = "anything"; var valueToCache = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()); TimeSpan timespan = TimeSpan.FromSeconds(10); Ttl ttl = new Ttl(timespan, false); IAsyncCacheProvider <byte[]> provider = mockDistributedCache.Object.AsAsyncCacheProvider <byte[]>(); Func <Task> action = () => provider.PutAsync(key, valueToCache, ttl, new CancellationToken(true), false); action.ShouldThrow <OperationCanceledException>(); }
public void PutAsync_should_throw_for_cancellation() { Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache> mockDistributedCache = new Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache>(); string key = "anything"; var valueToCache = "something to cache"; TimeSpan timespan = TimeSpan.FromSeconds(10); Ttl ttl = new Ttl(timespan, false); IAsyncCacheProvider <string> provider = mockDistributedCache.Object.AsAsyncCacheProvider <string>(); Func <Task> action = () => provider.PutAsync(key, valueToCache, ttl, new CancellationToken(true), false); action.ShouldThrow <OperationCanceledException>(); }
/// <summary> /// Initializes a new instance of the <see cref="SerializingCacheProviderAsync{TResult, TSerialized}"/> class. /// </summary> /// <param name="wrappedCacheProvider">The wrapped cache provider.</param> /// <param name="serializer">The serializer.</param> /// <exception cref="System.ArgumentNullException">wrappedCacheProvider </exception> /// <exception cref="System.ArgumentNullException">serializer </exception> public SerializingCacheProviderAsync(IAsyncCacheProvider <TSerialized> wrappedCacheProvider, ICacheItemSerializer <object, TSerialized> serializer) { if (wrappedCacheProvider == null) { throw new ArgumentNullException(nameof(wrappedCacheProvider)); } if (serializer == null) { throw new ArgumentNullException(nameof(serializer)); } _wrappedCacheProvider = wrappedCacheProvider; _serializer = serializer; }
public static void GetPolicyRegistry(IAsyncCacheProvider cacheProvider, IPolicyRegistry <string> registry) { registry.Add("thriceTriplingRetryPolicy", Policy.HandleResult <HttpResponseMessage>(r => !r.IsSuccessStatusCode) .Or <TimeoutRejectedException>() .WaitAndRetryAsync(thriceTriplingTimeSpans)); registry.Add("loginResponseRetryPolicy", Policy.HandleResult <LoginResponse>(lr => lr.LoginStatus != _successfulLoginStatus) .Or <TimeoutRejectedException>() .WaitAndRetryAsync(thriceTriplingTimeSpans)); registry.Add("thirtySecondTimeoutPolicy", Policy.TimeoutAsync(TimeSpan.FromSeconds(30))); AsyncCachePolicy <LoginResponse> cachePolicy = Policy.CacheAsync <LoginResponse>(cacheProvider, _timeToLive); registry.Add("oneMinuteLoginCachePolicy", cachePolicy); }
public async Task GetAsync_should_return_instance_previously_stored_in_cache() { Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache> mockDistributedCache = new Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache>(); string key = "anything"; var cachedValue = new byte[] { 0 }; mockDistributedCache.Setup(idc => idc.GetAsync(It.Is <string>(k => k == key))).Returns(Task.FromResult(cachedValue)).Verifiable(); IAsyncCacheProvider <byte[]> provider = mockDistributedCache.Object.AsAsyncCacheProvider <byte[]>(); byte[] got = await provider.GetAsync(key, CancellationToken.None, false); mockDistributedCache.Verify(v => v.GetAsync(key), Times.Once); got.Should().BeSameAs(cachedValue); }
public async Task GetAsync_should_return_null_on_unknown_key() { Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache> mockDistributedCache = new Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache>(); string key = "anything"; mockDistributedCache.Setup(idc => idc.GetAsync(It.Is <string>(k => k == key))).Returns(Task.FromResult(new byte[0] { })).Verifiable(); // Because GetStringAsync() is an extension method, we cannot mock it. We mock GetAsync() instead. IAsyncCacheProvider <string> provider = mockDistributedCache.Object.AsAsyncCacheProvider <string>(); string someOtherKey = Guid.NewGuid().ToString(); string got = await provider.GetAsync(someOtherKey, CancellationToken.None, false); mockDistributedCache.Verify(v => v.GetAsync(someOtherKey), Times.Once); got.Should().BeNull(); }
public async Task PutAsync_should_put_item_using_passed_sliding_ttl() { Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache> mockDistributedCache = new Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache>(); string key = "anything"; var valueToCache = new byte[] { 0 }; IAsyncCacheProvider <byte[]> provider = mockDistributedCache.Object.AsAsyncCacheProvider <byte[]>(); mockDistributedCache.Setup(idc => idc.SetAsync(It.Is <string>(k => k == key), It.Is <byte[]>(v => v == valueToCache), It.IsAny <DistributedCacheEntryOptions>())).Returns(Task.CompletedTask).Verifiable(); TimeSpan timespan = TimeSpan.FromSeconds(10); Ttl ttl = new Ttl(timespan, true); await provider.PutAsync(key, valueToCache, ttl, CancellationToken.None, false); mockDistributedCache.Verify(idc => idc.SetAsync(key, valueToCache, It.Is <DistributedCacheEntryOptions>(o => o.SlidingExpiration == timespan))); }
public async Task GetAsync_should_return_null_on_unknown_key() { Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache> mockDistributedCache = new Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache>(); string key = "anything"; var cachedValue = new byte[] { 0 }; mockDistributedCache.Setup(idc => idc.GetAsync(It.Is <string>(k => k == key))).Returns(Task.FromResult(cachedValue)).Verifiable(); IAsyncCacheProvider <byte[]> provider = mockDistributedCache.Object.AsAsyncCacheProvider <byte[]>(); string someOtherKey = Guid.NewGuid().ToString(); byte[] got = await provider.GetAsync(someOtherKey, CancellationToken.None, false); mockDistributedCache.Verify(v => v.GetAsync(someOtherKey), Times.Once); got.Should().BeNull(); }
/// <summary> /// <para>Builds a <see cref="Policy" /> that will function like a result cache for delegate executions returning a result.</para> /// <para>Before executing a delegate returning a result, checks whether the <paramref name="cacheProvider" /> holds a value for the cache key determined by applying the <paramref name="cacheKeyStrategy"/> to the execution <see cref="Context"/>. /// If the <paramref name="cacheProvider" /> provides a value, returns that value and does not execute the governed delegate. If the <paramref name="cacheProvider" /> does not provide a value, executes the governed delegate, stores the value with the <paramref name="cacheProvider" />, then returns the value. /// </para> /// </summary> /// <param name="cacheProvider">The cache provider.</param> /// <param name="ttlStrategy">A strategy for specifying ttl for values to be cached.</param> /// <param name="cacheKeyStrategy">The cache key strategy.</param> /// <param name="onCacheGet">Delegate to call on a cache hit, when value is returned from cache.</param> /// <param name="onCacheMiss">Delegate to call on a cache miss.</param> /// <param name="onCachePut">Delegate to call on cache put.</param> /// <param name="onCacheGetError">Delegate to call if an exception is thrown when attempting to get a value from the cache, passing the execution context, the cache key, and the exception.</param> /// <param name="onCachePutError">Delegate to call if an exception is thrown when attempting to put a value in the cache, passing the execution context, the cache key, and the exception.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">cacheProvider</exception> /// <exception cref="ArgumentNullException">ttlStrategy</exception> /// <exception cref="ArgumentNullException">cacheKeyStrategy</exception> /// <exception cref="ArgumentNullException">onCacheGet</exception> /// <exception cref="ArgumentNullException">onCacheMiss</exception> /// <exception cref="ArgumentNullException">onCachePut</exception> /// <exception cref="ArgumentNullException">onCacheGetError</exception> /// <exception cref="ArgumentNullException">onCachePutError</exception> public static CachePolicy CacheAsync( IAsyncCacheProvider cacheProvider, ITtlStrategy ttlStrategy, Func <Context, string> cacheKeyStrategy, Action <Context, string> onCacheGet, Action <Context, string> onCacheMiss, Action <Context, string> onCachePut, Action <Context, string, Exception> onCacheGetError, Action <Context, string, Exception> onCachePutError) { if (cacheProvider == null) { throw new ArgumentNullException(nameof(cacheProvider)); } if (ttlStrategy == null) { throw new ArgumentNullException(nameof(ttlStrategy)); } if (cacheKeyStrategy == null) { throw new ArgumentNullException(nameof(cacheKeyStrategy)); } if (onCacheGet == null) { throw new ArgumentNullException(nameof(onCacheGet)); } if (onCacheMiss == null) { throw new ArgumentNullException(nameof(onCacheMiss)); } if (onCachePut == null) { throw new ArgumentNullException(nameof(onCachePut)); } if (onCachePutError == null) { throw new ArgumentNullException(nameof(onCachePutError)); } if (onCachePutError == null) { throw new ArgumentNullException(nameof(onCachePutError)); } return(new CachePolicy(cacheProvider, ttlStrategy, cacheKeyStrategy, onCacheGet, onCacheMiss, onCachePut, onCacheGetError, onCachePutError)); }
/// <summary> /// <para>Builds a <see cref="Policy" /> that will function like a result cache for delegate executions returning a result.</para> /// <para>Before executing a delegate returning a result, checks whether the <paramref name="cacheProvider" /> holds a value for the cache key determined by applying the <paramref name="cacheKeyStrategy"/> to the execution <see cref="Context"/>. /// If the <paramref name="cacheProvider" /> provides a value, returns that value and does not execute the governed delegate. If the <paramref name="cacheProvider" /> does not provide a value, executes the governed delegate, stores the value with the <paramref name="cacheProvider" />, then returns the value. /// </para> /// </summary> /// <param name="cacheProvider">The cache provider.</param> /// <param name="ttlStrategy">A strategy for specifying ttl for values to be cached.</param> /// <param name="cacheKeyStrategy">The cache key strategy.</param> /// <param name="onCacheError">Delegate to call if an exception is thrown when attempting to get a value from or put a value into the cache, passing the execution context, the cache key, and the exception.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">cacheProvider</exception> /// <exception cref="ArgumentNullException">ttlStrategy</exception> /// <exception cref="ArgumentNullException">cacheKeyStrategy</exception> public static CachePolicy CacheAsync(IAsyncCacheProvider cacheProvider, ITtlStrategy ttlStrategy, Func <Context, string> cacheKeyStrategy, Action <Context, string, Exception> onCacheError = null) { if (cacheProvider == null) { throw new ArgumentNullException(nameof(cacheProvider)); } if (ttlStrategy == null) { throw new ArgumentNullException(nameof(ttlStrategy)); } if (cacheKeyStrategy == null) { throw new ArgumentNullException(nameof(cacheKeyStrategy)); } onCacheError = onCacheError ?? ((_, __, ___) => { }); Action <Context, string> emptyDelegate = (_, __) => { }; return(new CachePolicy(cacheProvider, ttlStrategy, cacheKeyStrategy, emptyDelegate, emptyDelegate, emptyDelegate, onCacheError, onCacheError)); }
internal AsyncCachePolicy( IAsyncCacheProvider asyncCacheProvider, ITtlStrategy ttlStrategy, Func <Context, string> cacheKeyStrategy, Action <Context, string> onCacheGet, Action <Context, string> onCacheMiss, Action <Context, string> onCachePut, Action <Context, string, Exception> onCacheGetError, Action <Context, string, Exception> onCachePutError) { _asyncCacheProvider = asyncCacheProvider; _ttlStrategy = ttlStrategy; _cacheKeyStrategy = cacheKeyStrategy; _onCacheGet = onCacheGet; _onCachePut = onCachePut; _onCacheMiss = onCacheMiss; _onCacheGetError = onCacheGetError; _onCachePutError = onCachePutError; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAsyncCacheProvider cacheProvider, IPolicyRegistry <string> registry) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WeatherService v1")); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); registry.Add("CachingPolicy", Policy.CacheAsync <HttpResponseMessage>(cacheProvider, TimeSpan.FromSeconds(30))); }
public RAWGClient(IConfiguration configuration, IAsyncCacheProvider cacheProvider, HttpClient httpClient) { _apiKey = configuration.GetValue <string>(CONFIG_API_KEY); if (string.IsNullOrEmpty(_apiKey)) { throw new ArgumentNullException($"The configuration value '{CONFIG_API_KEY}' is not set."); } _baseUrl = configuration.GetValue <string>(CONFIG_BASE_URL); if (string.IsNullOrEmpty(_baseUrl)) { throw new ArgumentNullException($"The configuration value '{CONFIG_BASE_URL}' is not set."); } _httpClient = httpClient; // Build a basic retry policy for request failures var retryPolicy = Policy .Handle <HttpRequestException>() .WaitAndRetryAsync(new [] { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), }); var gameCacheTTL = configuration.GetValue <int?>(CONFIG_GAME_CACHE_TTL) ?? DEFAULT_GAME_CACHE_TTL; // Game requests have caching and retry for fault tolerance _gamePolicy = Policy .WrapAsync( Policy.CacheAsync( cacheProvider, TimeSpan.FromMinutes(gameCacheTTL)), retryPolicy) .AsAsyncPolicy <GameResponse>(); // Games requests have just retry for fault tolerance _gamesPolicy = retryPolicy.AsAsyncPolicy <GamesResponse>(); }
/// <summary> /// 创建多级缓存提供程序对象 /// </summary> /// <param name="l1Cache">一级缓存</param> /// <param name="l2Cache">二级缓存</param> public MultiCacheProvider( IAsyncCacheProvider l1Cache, IAsyncL2CacheProvider l2Cache ) { L1Cache = l1Cache; L2Cache = l2Cache; }