Skip to content

Instantly share code, notes, and snippets.

@skaveesh
Last active January 3, 2021 04:36
Show Gist options
  • Save skaveesh/b067c35af63b3463bd6a14b68426ee4a to your computer and use it in GitHub Desktop.
Save skaveesh/b067c35af63b3463bd6a14b68426ee4a to your computer and use it in GitHub Desktop.
How I Decoupled Circuit Breaker from the Code with AOP in Spring Boot for Better Code Maintenance
//code is omitted for brevity
@Service
public class DownstreamService {
private final CircuitBreaker circuitBreaker;
/**
* Instantiates a new Res 4 j service.
*/
public DownstreamService(CircuitBreakerRegistry circuitBreakerRegistry) {
this.circuitBreaker = circuitBreakerRegistry.circuitBreaker("myAPOConfiguredMyCircuitBreaker");
}
//code is omitted for brevity
public JSONObject callTestSlow() {
Supplier<Object> supplier = () -> {
JSONObject result;
try
{
String serviceUrl = "http://localhost:3000/testslow";
RestTemplate restTemplate = new RestTemplate();
result = restTemplate.getForObject(serviceUrl, JSONObject.class);
} catch (HttpClientErrorException ex)
{
throw new RuntimeException("external API error");
} catch (Exception ex)
{
throw new RuntimeException("server error");
}
JSONObject payloadJSONObject = new JSONObject();
payloadJSONObject.putAll(result);
return payloadJSONObject;
};
return (JSONObject) this.execute(supplier, this::fallback);
}
private <T> T execute(Supplier<T> supplier, Function<Throwable, T> fallback) {
return Decorators.ofSupplier(supplier)
.withCircuitBreaker(circuitBreaker)
.withFallback(fallback)
.get();
}
private ResponseEntity<String> fallback(Throwable ex) {
throw new CircuitBreakerDownstreamCallException(ex.getMessage());
}
//code is omitted for brevity
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment