How do I use a circuit breaker?

后端 未结 2 1205
独厮守ぢ
独厮守ぢ 2021-02-19 05:18

I\'m looking for ways to make remote calls to services out of my control until a connect is successful. I also don\'t want to simply set a timer where an action gets executed ev

2条回答
  •  长发绾君心
    2021-02-19 05:34

    I've created a library called CircuitBreaker.Net that encapsulates all serving logic to safely perform calls. It's easy to use, an example could look like:

    // Initialize the circuit breaker
    var circuitBreaker = new CircuitBreaker(
        TaskScheduler.Default,
        maxFailures: 3,
        invocationTimeout: TimeSpan.FromMilliseconds(100),
        circuitResetTimeout: TimeSpan.FromMilliseconds(10000));
    
    try
    {
        // perform a potentially fragile call through the circuit breaker
        circuitBreaker.Execute(externalService.Call);
        // or its async version
        // await circuitBreaker.ExecuteAsync(externalService.CallAsync);
    }
    catch (CircuitBreakerOpenException)
    {
        // the service is unavailable, failover here
    }
    catch (CircuitBreakerTimeoutException)
    {
        // handle timeouts
    }
    catch (Exception)
    {
        // handle other unexpected exceptions
    }
    

    It's available via a nuget package. You can find the sources on github.

提交回复
热议问题