Implementing timeout

Timeout is a proactive policy, which is applicable in scenarios where the target service takes a long time to respond, and rather than letting the client wait for a response, we return a general message or response. We can use the same Polly framework to define the timeout policy, and it can also be used with the combination of retry and circuit breaker patterns we learned earlier:

In the preceding diagram, the user registration service is calling the email service to send emails. Now, if the email service does not respond in a particular amount of time, as specified in the timeout policy, the timeout exception will be raised.

To add a timeout policy, declare a _timeoutPolicy variable in the ResilientHttpClient class:

static TimeoutPolicy<HttpResponseMessage> _timeoutPolicy; 

Then, add the following code to initialize the timeout policy:

_timeoutPolicy = Policy.Timeout<HttpResponseMessage>(1); 

Finally, we will wrap the timeout policy and add it in resiliencyPolicyWrap. Here is the modified code of the ExecuteWithRetryandCircuitBreaker method:

public HttpResponseMessage ExecuteWithRetryandCircuitBreaker(string uri, Func<HttpResponseMessage> func) 
{ 
 
  PolicyWrap<HttpResponseMessage> resiliencePolicyWrap = 
Policy.Wrap(_timeoutPolicy, _retryPolicy, _circuitBreakerPolicy); PolicyWrap<HttpResponseMessage> fallbackPolicyWrap =
_fallbackPolicy.Wrap(_fallbackCircuitBreakerPolicy.Wrap(resiliencePolicyWrap)); var res = fallbackPolicyWrap.Execute(() => func()); return res; }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.212.124