按照入门指南 ( https://resilience4j.readme.io/docs/getting-started-3 ) 和演示项目 ( https://github.com/resilience4j/resilience4j-spring-boot2-demo ) 我想自己测试它,创建一个更简单的测试应用程序。
这是代码:
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();
}
}
控制器:
@RestController
public class ServiceController {
@Autowired
private AlbumService albumService;
@GetMapping("/albums")
ResponseEntity<String> getAlbums() {
return albumService.getAlbums();
}
}
和服务类:
@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);
}
}
最后是应用程序文件:
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
我引入了一个概率为 70% 的随机错误来测试断路器。但是,电路永远不会打开,我总是会出错。我不知道我错过了什么!有什么帮助吗?