Пример #1
0
        /// <summary>
        ///     Wrap policy
        /// </summary>
        /// <param name="key"></param>
        /// <param name="duration"></param>
        /// <returns></returns>
        private AsyncPolicyWrap <string> GetPolicyWrap(string key, TimeSpan?duration)
        {
            PolicyRegistry registry = new PolicyRegistry
            {
                // https://github.com/App-vNext/Polly/wiki/Cache
                { key, Policy.CacheAsync <string>(
                      cacheProvider: _cache.AsAsyncCacheProvider <string>(),
                      ttlStrategy: new RelativeTtl(duration ?? DefaultTimeToLive),
                      //new ContextualTtl(), used with context[ContextualTtl.TimeSpanKey], define ttl in different calls
                      //new SlidingTtl(duration ?? DefaultTimeToLive), each time the cache item is touched, ttl extend.
                      //new ResultTtl(), used for vary ttl base on T model pass in
                      cacheKeyStrategy: (ctx) => ctx.OperationKey,   //OperationKey is default cacheKey
                      onCacheGet: (ctx, cacheKey) => Console.WriteLine($"Get : {cacheKey}"),
                      onCacheMiss: (ctx, cacheKey) => Console.WriteLine($"Miss : {cacheKey}"),
                      onCachePut: (ctx, cacheKey) => Console.WriteLine($"Put : {cacheKey}"),
                      onCacheGetError: (ctx, str, ex) => throw ex,
                      onCachePutError: (ctx, str, ex) => throw ex) }
            };

            var asyncPolicy = registry.Get <IAsyncPolicy <string> >(key);

            return(Policy
                   .Handle <IOException>()
                   .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)))
                   .WrapAsync(asyncPolicy));
        }