/// <summary> /// Adds a set of rety and circuit breaker policies to the given policy registery with the given service name. /// </summary> /// <typeparam name="TService">The service for which the policies are being setup.</typeparam> /// <param name="services">The <see cref="IServiceCollection"/> to add the feature's services to.</param> /// <param name="config">The <see cref="IConfiguration"/> that defines Polly policy settings.</param> /// <param name="policyRegistry">The <see cref="IPolicyRegistry{TKey}"/> to add the new policies to.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public static IServiceCollection AddPolicies <TService>( this IServiceCollection services, IConfiguration config, IPolicyRegistry <string> policyRegistry) { var policyOptions = new HttpPolicyOptions(); config.GetSection(nameof(HttpPolicyOptions)).Bind(policyOptions); policyRegistry?.Add( $"{typeof(TService).Name}_{PolicyType.Retry}", HttpPolicyExtensions .HandleTransientHttpError() .WaitAndRetryAsync( policyOptions.HttpRetryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(policyOptions.HttpRetryBackoffPower, retryAttempt)))); policyRegistry?.Add( $"{typeof(TService).Name}_{PolicyType.CircuitBreaker}", HttpPolicyExtensions .HandleTransientHttpError() .CircuitBreakerAsync( handledEventsAllowedBeforeBreaking: policyOptions.CircuitBreakerToleranceCount, durationOfBreak: policyOptions.CircuitBreakerDurationOfBreak)); return(services); }
private static IServiceCollection ConfigurePolicies(this IServiceCollection services) { IPolicyRegistry <string> registry = services.AddPolicyRegistry(); IAsyncPolicy <HttpResponseMessage> httpWaitAndpRetryPolicy = Policy.HandleResult <HttpResponseMessage>(r => !r.IsSuccessStatusCode) .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt) / 2), onRetry: (httpResponseMessage, retryCount) => { // Log Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"Request failed...{httpResponseMessage.Result.StatusCode}"); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"Retrying..."); Console.ForegroundColor = ConsoleColor.White; }); registry.Add(nameof(httpWaitAndpRetryPolicy), httpWaitAndpRetryPolicy); IAsyncPolicy <HttpResponseMessage> noOpPolicy = Policy.NoOpAsync() .AsAsyncPolicy <HttpResponseMessage>(); registry.Add(nameof(noOpPolicy), noOpPolicy); return(services); }
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); IPolicyRegistry <string> registry = services.AddPolicyRegistry(); IAsyncPolicy <HttpResponseMessage> _httpRetryPolicy = Policy.HandleResult <HttpResponseMessage>(r => !r.IsSuccessStatusCode) .Or <TimeoutRejectedException>() .RetryAsync(3); registry.Add("SimpleHttpRetryPolicy", _httpRetryPolicy); IAsyncPolicy <HttpResponseMessage> httpWaitAndRetryPolicy = Policy.HandleResult <HttpResponseMessage>(r => !r.IsSuccessStatusCode) .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt)); registry.Add("SimpleWaitAndRetryPolicy", httpWaitAndRetryPolicy); IAsyncPolicy <HttpResponseMessage> noOpPolicy = Policy.NoOpAsync().AsAsyncPolicy <HttpResponseMessage>(); registry.Add("NoOpPolicy", noOpPolicy); services.AddHttpClient(PollyConstants.RemoteServer, client => { client.BaseAddress = new Uri("http://localhost:58042/api/"); client.DefaultRequestHeaders.Add("Accept", "application/json"); }).AddPolicyHandlerFromRegistry(PolicySelector); }
public static IServiceCollection AddPolicies( this IServiceCollection services, IPolicyRegistry <string> policyRegistry, string keyPrefix, PolicyOptions policyOptions) { if (policyOptions != null) { policyRegistry?.Add( $"{keyPrefix}_{nameof(PolicyOptions.HttpRetry)}", HttpPolicyExtensions .HandleTransientHttpError() .WaitAndRetryAsync( policyOptions.HttpRetry.Count, retryAttempt => TimeSpan.FromSeconds(Math.Pow(policyOptions.HttpRetry.BackoffPower, retryAttempt)))); policyRegistry?.Add( $"{keyPrefix}_{nameof(PolicyOptions.HttpCircuitBreaker)}", HttpPolicyExtensions .HandleTransientHttpError() .CircuitBreakerAsync( handledEventsAllowedBeforeBreaking: policyOptions.HttpCircuitBreaker.ExceptionsAllowedBeforeBreaking, durationOfBreak: policyOptions.HttpCircuitBreaker.DurationOfBreak)); return(services); } throw new InvalidOperationException($"{nameof(policyOptions)} is null"); }
public static IPolicyRegistry <string> AddStandardPolicies( this IPolicyRegistry <string> policyRegistry, string keyPrefix, CorePolicyOptions policyOptions) { if (policyOptions == null) { throw new ArgumentException("policyOptions cannot be null", nameof(policyOptions)); } if (policyRegistry == null) { throw new ArgumentException("policyRegistry cannot be null", nameof(policyRegistry)); } policyRegistry.Add( $"{keyPrefix}_{nameof(CorePolicyOptions.HttpRetry)}", HttpPolicyExtensions .HandleTransientHttpError() .WaitAndRetryAsync( policyOptions.HttpRetry.Count, retryAttempt => TimeSpan.FromSeconds(Math.Pow(policyOptions.HttpRetry.BackoffPower, retryAttempt)))); policyRegistry.Add( $"{keyPrefix}_{nameof(CorePolicyOptions.HttpCircuitBreaker)}", HttpPolicyExtensions .HandleTransientHttpError() .CircuitBreakerAsync( handledEventsAllowedBeforeBreaking: policyOptions.HttpCircuitBreaker.ExceptionsAllowedBeforeBreaking, durationOfBreak: policyOptions.HttpCircuitBreaker.DurationOfBreak)); return(policyRegistry); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSingleton(GetRegistry()); IAsyncPolicy <HttpResponseMessage> httpRetryPolicy = Policy.HandleResult <HttpResponseMessage>(r => !r.IsSuccessStatusCode) .RetryAsync(3); IAsyncPolicy <HttpResponseMessage> noPolicy = Policy.NoOpAsync <HttpResponseMessage>(); // Polly Single Policy //services.AddHttpClient("RemoteServer", client => //{ // client.BaseAddress = new Uri("https://localhost:44363/"); // client.DefaultRequestHeaders.Add("Accept", "application/json"); //}).AddPolicyHandler(httpRetryPolicy); IPolicyRegistry <string> registry = services.AddPolicyRegistry(); registry.Add("SimpleRetry", httpRetryPolicy); registry.Add("NoOp", noPolicy); services.AddHttpClient("RemoteServer", client => { client.BaseAddress = new Uri("https://localhost:44363/"); client.DefaultRequestHeaders.Add("Accept", "application/json"); }).AddPolicyHandlerFromRegistry(PolicySelector); services.AddControllers(); }
public static void AddPolicies(this IServiceCollection services) { IPolicyRegistry <string> registry = services.AddPolicyRegistry(); Random jitterer = new Random(); var policyGSync = Policy.Handle <Exception>(ex => !(ex is GoogleApiException || ex is NegocioException)) .WaitAndRetryAsync(3, // exponential back-off plus some jitter retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)) + TimeSpan.FromMilliseconds(jitterer.Next(0, 30))); registry.Add(PoliticaPolly.PolicyGoogleSync, policyGSync); var policyFilas = Policy.Handle <Exception>() .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(5)); registry.Add(PoliticaPolly.PolicyPublicaFila, policyFilas); var policyGSyncRemocaoProfessor = Policy.Handle <Exception>() .WaitAndRetryAsync(new[] { TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(60) }, (exception, timeSpan, retryCount, context) => { Console.WriteLine($"RETRY policyGSyncRemocaoProfessor - {retryCount}: {exception.Message}"); }); //.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(30)); registry.Add(PoliticaPolly.PolicyRemocaoProfessor, policyGSyncRemocaoProfessor); RegistrarPolicyGsa(registry); }
/// <summary> /// /// </summary> /// <param name="services"></param> /// <param name="configureClient"></param> /// <returns></returns> private static IHttpClientBuilder AddHttpClient(this IServiceCollection services, Action <HttpClient> configureClient) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (configureClient == null) { throw new ArgumentNullException(nameof(configureClient)); } IPolicyRegistry <string> registry = services.AddPolicyRegistry(); var timeout = Policy.TimeoutAsync <HttpResponseMessage>(TimeSpan.FromSeconds(10)); var longTimeout = Policy.TimeoutAsync <HttpResponseMessage>(TimeSpan.FromSeconds(60)); registry.Add("regular", timeout); registry.Add("long", longTimeout); return(services.AddHttpClient("SFExpress", configureClient) .AddPolicyHandler(Policy.TimeoutAsync <HttpResponseMessage>(TimeSpan.FromSeconds(100))) .AddPolicyHandlerFromRegistry("regular") .AddPolicyHandler((request) => { return request.Method == HttpMethod.Get ? timeout : longTimeout; }) .AddPolicyHandlerFromRegistry((reg, request) => { return request.Method == HttpMethod.Get ? reg.Get <IAsyncPolicy <HttpResponseMessage> >("regular") : reg.Get <IAsyncPolicy <HttpResponseMessage> >("long"); }) .AddTransientHttpErrorPolicy(p => p.RetryAsync()) .AddHttpMessageHandler(() => new RetryHandler()) .AddTypedClient <SfExpressService>()); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { IPolicyRegistry <string> registry = services.AddPolicyRegistry(); IAsyncPolicy <HttpResponseMessage> httpRetryPolicy = Policy.HandleResult <HttpResponseMessage>(r => !r.IsSuccessStatusCode) .RetryAsync(3); registry.Add("SimpleHttpRetryPolicy", httpRetryPolicy); IAsyncPolicy <HttpResponseMessage> httWaitAndpRetryPolicy = Policy.HandleResult <HttpResponseMessage>(r => !r.IsSuccessStatusCode) .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt)); registry.Add("SimpleWaitAndRetryPolicy", httWaitAndpRetryPolicy); IAsyncPolicy <HttpResponseMessage> noOpPolicy = Policy.NoOpAsync() .AsAsyncPolicy <HttpResponseMessage>(); registry.Add("NoOpPolicy", noOpPolicy); services.AddHttpClient("RemoteServer", client => { client.BaseAddress = new Uri("http://localhost:57696/api/"); client.DefaultRequestHeaders.Add("Accept", "application/json"); }).AddPolicyHandlerFromRegistry((PolicySelector)); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
public static IServiceCollection AddPolicies( this IServiceCollection services, IPolicyRegistry <string> policyRegistry, string keyPrefix, PolicyOptions policyOptions) { _ = policyOptions ?? throw new ArgumentNullException(nameof(policyOptions)); policyRegistry?.Add( $"{keyPrefix}_{nameof(PolicyOptions.HttpRetry)}", HttpPolicyExtensions .HandleTransientHttpError() .OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.TooManyRequests) .OrResult(r => r?.Headers?.RetryAfter != null) .WaitAndRetryAsync( policyOptions.HttpRetry.Count, retryAttempt => TimeSpan.FromSeconds(Math.Pow(policyOptions.HttpRetry.BackoffPower, retryAttempt)))); policyRegistry?.Add( $"{keyPrefix}_{nameof(PolicyOptions.HttpCircuitBreaker)}", HttpPolicyExtensions .HandleTransientHttpError() .CircuitBreakerAsync( handledEventsAllowedBeforeBreaking: policyOptions.HttpCircuitBreaker.ExceptionsAllowedBeforeBreaking, durationOfBreak: policyOptions.HttpCircuitBreaker.DurationOfBreak)); return(services); }
private static void AddPolicies(IPolicyRegistry <string> policyRegistry) { var policyOptions = new PolicyOptions() { HttpRetry = new RetryPolicyOptions(), HttpCircuitBreaker = new CircuitBreakerPolicyOptions() }; policyRegistry.Add(nameof(PolicyOptions.HttpRetry), HttpPolicyExtensions.HandleTransientHttpError().WaitAndRetryAsync(policyOptions.HttpRetry.Count, retryAttempt => TimeSpan.FromSeconds(Math.Pow(policyOptions.HttpRetry.BackoffPower, retryAttempt)))); policyRegistry.Add(nameof(PolicyOptions.HttpCircuitBreaker), HttpPolicyExtensions.HandleTransientHttpError().CircuitBreakerAsync(policyOptions.HttpCircuitBreaker.ExceptionsAllowedBeforeBreaking, policyOptions.HttpCircuitBreaker.DurationOfBreak)); }
public void Should_be_able_to_retrieve_stored_Policy_using_TryGet() { Policy policy = Policy.NoOp(); string key = Guid.NewGuid().ToString(); Policy outPolicy = null; _registry.Add(key, policy); ReadOnlyRegistry.TryGet(key, out outPolicy).Should().BeTrue(); outPolicy.Should().BeSameAs(policy); }
public bool TryAdd <TPolicy>(string key, TPolicy policy) where TPolicy : ICircuitBreakerPolicy { var added = false; lock (_lock) { if (!Registry.ContainsKey(key)) { Registry.Add(key, policy); added = true; } } return(added); }
static async Task Main(string[] args) { _config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .Build(); var builder = new HostBuilder() .ConfigureServices((hostContext, services) => { services.Configure <LastFmSettings>(_config.GetSection("LastFmSettings")); IPolicyRegistry <string> registry = services.AddPolicyRegistry(); IAsyncPolicy <HttpResponseMessage> httWaitAndpRetryPolicy = Policy.HandleResult <HttpResponseMessage>(r => !r.IsSuccessStatusCode) .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt)); registry.Add("SimpleWaitAndRetryPolicy", httWaitAndpRetryPolicy); IAsyncPolicy <HttpResponseMessage> noOpPolicy = Policy.NoOpAsync() .AsAsyncPolicy <HttpResponseMessage>(); registry.Add("NoOpPolicy", noOpPolicy); services.AddHttpClient("LastFmClient", client => { client.BaseAddress = new Uri(_config.GetValue <string>("LastFmSettings:BaseUrl")); client.DefaultRequestHeaders.Add("Accept", "application/json"); }).AddPolicyHandlerFromRegistry((policyRegistry, httpRequestMessage) => { if (httpRequestMessage.Method == HttpMethod.Get || httpRequestMessage.Method == HttpMethod.Delete) { return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("SimpleWaitAndRetryPolicy")); } return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("NoOpPolicy")); }); services.AddAutoMapper(); services.AddSingleton <IHostedService, Run>(); services.AddSingleton <IDatabaseService, DatabaseService>(); services.AddSingleton <IExtractorService, ExtractorService>(); services.AddSingleton <IUrlBuilderService, UrlBuilderService>(); services.AddSingleton <ITransformService, TransformService>(); AddMusicContextDb(services); }); await builder.RunConsoleAsync(); }
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 static void AdicionarPoliticas(this IServiceCollection services) { IPolicyRegistry <string> registry = services.AddPolicyRegistry(); IAsyncPolicy <HttpResponseMessage> httWaitAndpRetryPolicy = Policy.HandleResult <HttpResponseMessage>(r => !r.IsSuccessStatusCode) .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt)); registry.Add("PoliticaDeRetentativa", httWaitAndpRetryPolicy); IAsyncPolicy <HttpResponseMessage> noOpPolicy = Policy.NoOpAsync() .AsAsyncPolicy <HttpResponseMessage>(); registry.Add("SemPoliticaOp", noOpPolicy); }
/// <summary> /// 增加重试代码 /// </summary> /// <param name="services"></param> /// <param name="name"></param> /// <param name="configureClient"></param> /// <returns></returns> public static IHttpClientBuilder AddRetryHttpClient(this IServiceCollection services, string name, Action <HttpClient> configureClient) { if (services == null) { throw new ArgumentNullException("services"); } if (name == null) { throw new ArgumentNullException("name"); } if (configureClient == null) { throw new ArgumentNullException("configureClient"); } IPolicyRegistry <string> registry = services.AddPolicyRegistry(); Polly.Timeout.TimeoutPolicy <HttpResponseMessage> timeout = Policy.TimeoutAsync <HttpResponseMessage>(TimeSpan.FromSeconds(10)); Polly.Timeout.TimeoutPolicy <HttpResponseMessage> longTimeout = Policy.TimeoutAsync <HttpResponseMessage>(TimeSpan.FromSeconds(30)); registry.Add("regular", timeout); registry.Add("long", longTimeout); return(services.AddHttpClient(name, configureClient) // Build a totally custom policy using any criteria .AddPolicyHandler(Policy.TimeoutAsync <HttpResponseMessage>(TimeSpan.FromSeconds(10))) // Use a specific named policy from the registry. Simplest way, policy is cached for the // lifetime of the handler. .AddPolicyHandlerFromRegistry("regular") // Run some code to select a policy based on the request .AddPolicyHandler((request) => { return request.Method == HttpMethod.Get ? timeout : longTimeout; }) // Run some code to select a policy from the registry based on the request .AddPolicyHandlerFromRegistry((reg, request) => { return request.Method == HttpMethod.Get ? reg.Get <IAsyncPolicy <HttpResponseMessage> >("regular") : reg.Get <IAsyncPolicy <HttpResponseMessage> >("long"); }) // Build a policy that will handle exceptions, 408s, and 500s from the remote server .AddTransientHttpErrorPolicy(p => p.RetryAsync()) .AddHttpMessageHandler(() => new RetryHandler())); }
/// <summary> /// Adds Polly to the services. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add Polly to.</param> /// <returns> /// The value specified by <paramref name="services"/>. /// </returns> public static IServiceCollection AddPolly(this IServiceCollection services) { var sleepDurations = new[] { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10), }; var readPolicy = HttpPolicyExtensions.HandleTransientHttpError() .WaitAndRetryAsync(sleepDurations) .WithPolicyKey("ReadPolicy"); var writePolicy = Policy.NoOpAsync() .AsAsyncPolicy <HttpResponseMessage>() .WithPolicyKey("WritePolicy"); var policies = new[] { readPolicy, writePolicy, }; IPolicyRegistry <string> registry = services.AddPolicyRegistry(); foreach (var policy in policies) { registry.Add(policy.PolicyKey, policy); } return(services); }
private static void RegistrarPolicyGsa(IPolicyRegistry <string> registry) { var policy = Policy.Handle <Exception>() .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(60)); registry.Add(PoliticaPolly.PolicyCargaGsa, policy); }
public void TestInit() { _mockConfiguration = new Mock <IConfiguration>(); _mockConfiguration.Setup(c => c["BetfairApi:Url"]) .Returns("http://notarealurl.fab"); _mockConfiguration.Setup(c => c["BetfairApi:AppKeyHeader"]) .Returns("appkeyheader"); _mockConfiguration.Setup(c => c["BetfairApi:SessionTokenHeader"]) .Returns("sessiontokenheader"); _mockHttpMessageHandler = new Mock <HttpMessageHandler>(); _mockRegistry = new PolicyRegistry(); _mockRegistry.Add("thirtySecondTimeoutPolicy", _noOpPolicy); _mockRegistry.Add("thriceTriplingRetryPolicy", _noOpHttpResponsePolicy); }
/// <summary> /// Adds the specified <paramref name="policy"/> to the registry using /// the <see cref="IsPolicy.PolicyKey"/>. /// </summary> /// <param name="registry"> /// The <see cref="IPolicyRegistry{String}"/> to add policies to. /// </param> /// <param name="policy">The <see cref="IsPolicy"/> to add.</param> public static void Add(this IPolicyRegistry <string> registry, IsPolicy?policy) { if (registry != null && policy != null) { registry.Add(policy.PolicyKey, policy); } }
public static void CreateCachingPolicy <T>(this IServiceProvider provider, string cacheKey, ITtlStrategy strategy) { IPolicyRegistry <string> registry = provider.GetRequiredService <IPolicyRegistry <string> >(); IAsyncPolicy <T> policy = Policy.CacheAsync <T>(provider.GetRequiredService <IAsyncCacheProvider>().AsyncFor <T>(), strategy); registry.Add(cacheKey, policy); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IPolicyRegistry <string> policyRegistry, IAsyncCacheProvider memoryCache) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } Func <Context, HttpResponseMessage, Ttl> ttlFilter = (context, result) => new Ttl(result.IsSuccessStatusCode ? TimeSpan.FromSeconds(30) : TimeSpan.Zero); AsyncCachePolicy <HttpResponseMessage> policy = Policy.CacheAsync(memoryCache.AsyncFor <HttpResponseMessage>(), new ResultTtl <HttpResponseMessage>(ttlFilter)); policyRegistry.Add("cache", policy); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
public static IServiceCollection AddPolicies( this IServiceCollection services, IPolicyRegistry <string> policyRegistry, string retryPolicyKey, PolicyOptions policyOptions) { if (policyRegistry == null || policyOptions == null) { return(services); } policyRegistry.Add( retryPolicyKey, HttpPolicyExtensions .HandleTransientHttpError() .OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.TooManyRequests) .OrResult(msg => msg?.Headers?.RetryAfter != null) .WaitAndRetryAsync( policyOptions.HttpRetry.Count, retryAttempt => TimeSpan.FromMilliseconds(Math.Pow(policyOptions.HttpRetry.BackoffPower, retryAttempt) * policyOptions.HttpRetry.BackOffBaseMilliseconds))); return(services); }
private void ConfigurePolicies(IServiceCollection services) { policyRegistry = services.AddPolicyRegistry(); var timeoutPolicy = Policy.TimeoutAsync <HttpResponseMessage>(TimeSpan.FromMilliseconds(1500)); policyRegistry.Add("timeout", timeoutPolicy); }
public static void WaitAndRetry(ref IPolicyRegistry <string> registry, int retryCount = 5) => registry.Add("WaitAndRetry", HttpPolicyExtensions .HandleTransientHttpError() .OrResult(msg => msg.StatusCode == HttpStatusCode.NotFound) .Or <TimeoutRejectedException>() .WaitAndRetryAsync(retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));
private static void ConfigureRetryPolicy(IPolicyRegistry <string> registry) { var retryPolicy = Policy.Handle <HttpRequestException>() .OrTransientHttpError() .RetryAsync(2); registry.Add(RetryPolicyName, retryPolicy); }
private static async Task Main() { var builder = new HostBuilder() .ConfigureServices((hostContext, services) => { IPolicyRegistry <string> registry = services.AddPolicyRegistry(); IAsyncPolicy <HttpResponseMessage> httWaitAndRetryPolicy = Policy.HandleResult <HttpResponseMessage>(r => !r.IsSuccessStatusCode) .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt)); registry.Add("SimpleWaitAndRetryPolicy", httWaitAndRetryPolicy); IAsyncPolicy <HttpResponseMessage> noOpPolicy = Policy.NoOpAsync() .AsAsyncPolicy <HttpResponseMessage>(); registry.Add("NoOpPolicy", noOpPolicy); services.AddHttpClient("JsonplaceholderClient", client => { client.BaseAddress = new Uri("https://jsonplaceholder.typicode.com"); client.DefaultRequestHeaders.Add("Accept", "application/json"); }).AddPolicyHandlerFromRegistry((policyRegistry, httpRequestMessage) => { if (httpRequestMessage.Method == HttpMethod.Get) { return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("SimpleWaitAndRetryPolicy")); } return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("NoOpPolicy")); }); services.AddSingleton <IClientApi, ClientApi>(); services.AddSingleton <IClientFile, ClientFile>(); services.AddSingleton <IHostedService, App>(); services.AddTransient <App>() .AddLogging(loggingBuilder => { loggingBuilder.ClearProviders(); loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); loggingBuilder.AddNLog(); }); }); await builder.RunConsoleAsync(); }
public static IPolicyRegistry <string> AddTimeoutPolicy(this IPolicyRegistry <string> registerPolicy) { var timeoutPolicy = Policy .TimeoutAsync <HttpResponseMessage>(TimeSpan.FromSeconds(15)) .WithPolicyKey(PolicyNames.Timeout); registerPolicy.Add(PolicyNames.Timeout, timeoutPolicy); return(registerPolicy); }
private static void ConfigurePolly(IServiceCollection serviceCollection) { IPolicyRegistry <string> registry = serviceCollection.AddPolicyRegistry(); IAsyncPolicy <HttpResponseMessage> httpRetryPolicy = Policy .HandleResult <HttpResponseMessage>(r => !r.IsSuccessStatusCode).RetryAsync(3); registry.Add("SimpleRetryPolicy", httpRetryPolicy); IAsyncPolicy <HttpResponseMessage> httpRetryWaitPolicy = Policy .HandleResult <HttpResponseMessage>(r => !r.IsSuccessStatusCode) .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt) / 2)); registry.Add("WaitRetryPolicy", httpRetryWaitPolicy); IAsyncPolicy <HttpResponseMessage> noOpPolicy = Policy.NoOpAsync() .AsAsyncPolicy <HttpResponseMessage>(); registry.Add("NoOpPolicy", noOpPolicy); }