Following the getting started guide (https://resilience4j.readme.io/docs/getting-started-3) and the demo project (https://github.com/resilience4j/resilience4j-spring-boot2-demo) I wanted to test it by myself creating a simpler test application.
Here is the code:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ServiceConfiguration {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
Controller:
@RestController
public class ServiceController {
@Autowired
private AlbumService albumService;
@GetMapping("/albums")
ResponseEntity<String> getAlbums() {
return albumService.getAlbums();
}
}
And the service class:
@Slf4j
@Service
public class AlbumService {
@Autowired
private RestTemplate restTemplate;
@CircuitBreaker(name = "albumService", fallbackMethod = "getDefaultAlbumList")
public ResponseEntity<String> getAlbums() {
String url = MockNeat.secure().probabilites(String.class)
.add(0.7, "https://wrong-url.com")
.add(0.3, "https://jsonplaceholder.typicode.com/albums").val();
return new ResponseEntity<>(restTemplate.getForObject(url, String.class), HttpStatus.OK);
}
private ResponseEntity<String> getDefaultAlbumList(Exception ex) throws URISyntaxException, IOException {
log.info("Recovered: " + ex.getMessage());
return new ResponseEntity<>(new String(Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource("fallback-album-list.json").toURI()))), HttpStatus.OK);
}
}
Finally here the application file:
resilience4j:
circuitbreaker:
configs:
default:
registerHealthIndicator: true
slidingWindowSize: 10
minimumNumberOfCalls: 5
permittedNumberOfCallsInHalfOpenState: 3
automaticTransitionFromOpenToHalfOpenEnabled: true
waitDurationInOpenState: 5s
failureRateThreshold: 50
eventConsumerBufferSize: 10
instances:
albumService:
baseConfig: default
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: always
metrics:
distribution:
percentiles-histogram:
http:
server:
request: true
resielence4j:
circuitbreaker:
calls: true
I have introduced a random error with 70% probability to test the circuit breaker. However, the circuit never opens and I always get error. I have no idea what I am missing! Any help?