简体   繁体   中英

Using circuit breaker in spring boot

I have recently studied the circuit breaker pattern and I 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;
    }

}

There should only be one instance of circuit breaker for this client call. Creating a new instance with every API call will break the purpose as we are not maintaining the information about the previous requests.

I confirmed it with the community too: https://github.com/eugenp/tutorials/issues/12593

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM