Last active
January 3, 2021 04:36
-
-
Save skaveesh/73f71bb7a7b30e5c1960789350b893ca 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 | |
@Aspect | |
@Component | |
public class CircuitBreakerAOPConfig { | |
private static final Logger LOGGER = LoggerFactory.getLogger(CircuitBreakerAOPConfig.class); | |
private final CircuitBreaker circuitBreaker; | |
public CircuitBreakerAOPConfig(CircuitBreakerRegistry circuitBreakerRegistry){ | |
this.circuitBreaker = circuitBreakerRegistry.circuitBreaker("myAPOConfiguredMyCircuitBreaker"); | |
} | |
@Around("@annotation(com.skaveesh.dcb.annotation.EnableCircuitBreakerScan)") | |
public Object around(ProceedingJoinPoint proceedingJoinPoint) { | |
Object returnValue = execute(rethrowSupplier(proceedingJoinPoint::proceed), this::fallback); | |
LOGGER.info("Around after class - {}, method - {}, returns - {}", proceedingJoinPoint.getSignature().getDeclaringType().getName(), proceedingJoinPoint.getSignature().getName(), returnValue); | |
return returnValue; | |
} | |
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()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment