Last active
February 23, 2016 22:49
-
-
Save DavidBrower/a608e00960abad5b0a9f to your computer and use it in GitHub Desktop.
Polly Circuitbreaker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface ICircuitBreaker | |
{ | |
TResult Execute(Func action); | |
void Execute(Action action); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface ICircuitBreakerSettings | |
{ | |
int BreakOnNumberOfExceptions { get; } | |
int BreakCircuitForSeconds { get; } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PollyCircuitBreaker : ICircuitBreaker | |
{ | |
private readonly Policy _policy; | |
public PollyCircuitBreaker(ICircuitBreakerSettings settings) | |
{ | |
try | |
{ | |
_policy = Policy | |
.Handle<Exception>() | |
.CircuitBreaker(settings.BreakOnNumberOfExceptions, | |
TimeSpan.FromSeconds(settings.BreakCircuitForSeconds)); | |
} | |
catch (Exception ex) | |
{ | |
_policy = null; | |
//Log policy configuration issue | |
} | |
} | |
public TResult Execute<TResult>(Func<TResult> action) | |
{ | |
if (_policy == null) | |
{ | |
return action.Invoke(); | |
} | |
else | |
{ | |
try | |
{ | |
return _policy.Execute(action); | |
} | |
catch (BrokenCircuitException ex) | |
{ | |
throw new CircuitBrokenException("Broken circuit", ex); | |
} | |
} | |
} | |
public void Execute(Action action) | |
{ | |
if (_policy == null) | |
{ | |
action.Invoke(); | |
} | |
else | |
{ | |
try | |
{ | |
_policy.Execute(action); | |
} | |
catch (BrokenCircuitException ex) | |
{ | |
throw new CircuitBrokenException("Broken circuit", ex); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment