我正在解释弹簧云断路器,以解释她的https://www.baeldung.com/spring-cloud-circuit-breaker。 共3个服务。
(1)父服务(2)子服务(3)数据库。
我在调用子服务的API时在父服务上应用了CircuitBreaker(CB)。当我的数据库关闭时,子进程会向父进程抛出异常,因此父进程会切换到我配置的后备方法。
CB永远不会打开。每次父服务调用子服务时,即使下游数据库已关闭。
问题:
如果我在这里缺少任何配置,请帮助我。
@Bean
public Customizer<Resilience4JCircuitBreakerFactory> globalCustomConfiguration() {
CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
.failureRateThreshold(50)
.waitDurationInOpenState(Duration.ofMillis(1000))
.slidingWindowSize(5)
.build();
TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom()
.timeoutDuration(Duration.ofSeconds(4))
.build();
return factory -> factory.configure(builder -> builder.circuitBreakerConfig(circuitBreakerConfig)
.timeLimiterConfig(timeLimiterConfig).build(), "circuitBreaker5Sliding");
}
库存服务
@Service
public class InventoryService {
@Autowired
private CircuitBreakerFactory defaultCustomizer;
private static final Logger LOGGER = LoggerFactory.getLogger(InventoryService.class);
private RestTemplate restTemplate = new RestTemplate();
public List<Inventory> getInventories(String URI) {
CircuitBreaker circuitBreaker = defaultCustomizer.create("circuitBreaker5Sliding");
String url = "http://127.0.0.1:8086/" + URI;
LOGGER.info("url {}",url);
//Inventory[] items = circuitBreaker.run(() -> restTemplate.getForObject(url, Inventory[].class));
Inventory[] items = circuitBreaker.run(() -> restTemplate.getForObject(url, Inventory[].class),
throwable -> defaultItems());
LOGGER.info("List of inventories {}",items.length);
List<Inventory> itemList = Arrays.asList(items);
return itemList;
}
private Inventory[] defaultItems() {
try {
List<Inventory> inventories = new ArrayList<>();
Inventory default1 = new Inventory(4545L,1L, 2L,"default", 1);
inventories.add(default1);
return inventories.toArray(new Inventory[inventories.size()]);
} catch (Exception e) {
LOGGER.error("error occurred while reading the file", e);
}
return null;
}
}
Pom.xml