private PolicyRegistry BuildPolicyRegistry() { var circuitBreakerPolicy = Policy.Handle <HttpRequestException>() .CircuitBreakerAsync(1, TimeSpan.FromMinutes(1)); var memoryCache = new MemoryCache(new MemoryCacheOptions()); var memoryCacheProvider = new Polly.Caching.MemoryCache.MemoryCacheProvider(memoryCache); var cachePolicy = Policy.CacheAsync(memoryCacheProvider, TimeSpan.FromSeconds(30)); var cacheAndCircuitBreakerPolicy = cachePolicy.WrapAsync(Policy.Handle <HttpRequestException>() .CircuitBreakerAsync(1, TimeSpan.FromMinutes(1))); var fallbackCacheAndBreaker = Policy <Promotion> .Handle <BrokenCircuitException>() .Or <HttpRequestException>() .FallbackAsync <Promotion>(new Promotion() { Title = "Some Fallback Promotion", Description = "The Promotion API is down so we're showing something else", GeneratedTimestamp = DateTime.UtcNow } ) .WrapAsync(cacheAndCircuitBreakerPolicy); var registry = new PolicyRegistry(); registry.Add("PromoFallback", fallbackCacheAndBreaker); registry.Add("Promo", cacheAndCircuitBreakerPolicy); registry.Add("Merchant", circuitBreakerPolicy); return(registry); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IMemoryCache memoryCache) { Polly.Caching.IAsyncCacheProvider memoryCacheProvider = new Polly.Caching.MemoryCache.MemoryCacheProvider(memoryCache); CachePolicy <HttpResponseMessage> cachePolicy = Policy.CacheAsync <HttpResponseMessage>(memoryCacheProvider, TimeSpan.FromMinutes(5)); _myRegistry.Add("myLocalCachePolicy", cachePolicy); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); }
/// <summary> /// 缓存 /// </summary> private static void Caching() { //Install-Package Microsoft.Extensions.Caching.Memory Microsoft.Extensions.Caching.Memory.IMemoryCache memoryCache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions()); //Install-Package Polly.Caching.MemoryCache Polly.Caching.MemoryCache.MemoryCacheProvider memoryCacheProvider = new Polly.Caching.MemoryCache.MemoryCacheProvider(memoryCache); CachePolicy policy = Policy.Cache(memoryCacheProvider, TimeSpan.FromSeconds(5)); Random rand = new Random(); while (true) { int i = rand.Next(5); Console.WriteLine("产生" + i); var context = new Context("doublecache" + i); int result = policy.Execute(ctx => { Console.WriteLine("Execute计算" + i); return(i * 2); }, context); Console.WriteLine("计算结果:" + result); Thread.Sleep(500); } }