We are using YARP Reverse proxy to access multiple services. But not requirement came where we need to implement circuit breaker and retry policy into that proxy service but I didn't found any reference online to achieve that.
builder.Services.AddReverseProxy().LoadFromMemory().ConfigureHttpClient((context, handler) => {
});
Here I can see configure client extension method is available not don't know How to configure that. Wants to configure the below code with Httpclient.
public class CircuitBreakerAndRetryDelegatingHandler : DelegatingHandler
{
private readonly IOptionsMonitor<AppSettings> _appSettings;
private readonly IDisposable? _onChangeDisposable;
private AsyncPolicyWrap _circuitBreakerAndRetryPolicy;
public CircuitBreakerAndRetryDelegatingHandler(IOptionsMonitor<AppSettings> appSettings)
{
_appSettings = appSettings;
_onChangeDisposable = _appSettings.OnChange(x=> UpdateCircuitBreakerConfig());
UpdateCircuitBreakerConfig();
}
private void UpdateCircuitBreakerConfig()
{
var circuitBreakerPolicy = Policy.Handle<HttpRequestException>()
.CircuitBreakerAsync(exceptionsAllowedBeforeBreaking: 3, durationOfBreak: TimeSpan.FromSeconds(30));
var retryPolicy = Policy.Handle<HttpRequestException>()
.WaitAndRetryAsync(retryCount: 3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
_circuitBreakerAndRetryPolicy = Policy.WrapAsync(circuitBreakerPolicy, retryPolicy);
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return await _circuitBreakerAndRetryPolicy.ExecuteAsync(
async (cancellationToken) => await base.SendAsync(request, cancellationToken),
cancellationToken
);
}
}
Is there any way to achieve ?