I have recently studied the circuit breaker pattern and am doing a POC to implement it in my spring boot application. I found that spring provides an implementation of resilience4j out of the box.
I am studying an article who's github repo I am mentioniong below
https://github.com/eugenp/tutorials/blob/master/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/AlbumService.java
Code is as shown below. My doubt is in the higlighted statement
CircuitBreaker circuitBreaker = circuitBreakerFactory.create("circuitbreaker");
doesn't this mean that everytime getAlbumList() is callled a new instance of circuit breaker will be created and hence the old values of events registered by circuit breaker will be lost. Should there not be only one instance across application.
I am very confused here am I forgetting some basic priniciple of spring framework, please help me. I want to understand how this works.
@Service
public class AlbumService {
private static final Logger LOGGER = LoggerFactory.getLogger(AlbumService.class);
@Autowired
private CircuitBreakerFactory circuitBreakerFactory;
private RestTemplate restTemplate = new RestTemplate();
public String getAlbumList() {
**CircuitBreaker circuitBreaker = circuitBreakerFactory.create("circuitbreaker");**
String url = "https://jsonplaceholder.typicode.com/albums";
return circuitBreaker.run(() -> restTemplate.getForObject(url, String.class), throwable -> getDefaultAlbumList());
}
private String getDefaultAlbumList() {
try {
return new String(Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource("fallback-album-list.json").toURI())));
} catch (Exception e) {
LOGGER.error("error occurred while reading the file", e);
}
return null;
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…