Last active
January 3, 2021 04:36
-
-
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
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
//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