我正在探索弹簧云断路器,解释她https://www.baeldung.com/spring-cloud-circuit-breaker。共有 3 项服务。
(1) 父服务 (2) 子服务 (3) 数据库。
我在调用子服务的 API 时在父服务上应用了 CircuitBreaker(CB)。当我的数据库关闭时,子级向父级抛出异常,因此父级切换到我配置的后备方法。
CB 永远不会进入 OPEN。每次父服务调用子服务时,即使下游数据库已关闭。
问题:
- 父服务不应该停止调用子服务吗?
- 根据配置,5 个失败调用中的 3 个应该打开 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
- spring-cloud-starter-openfeign
- spring-cloud-openfeign-core
- 春季重试 1.2.4.RELEASE
- spring-cloud-starter-circuitbreaker-resilience4j 1.0.3.RELEASE
- 弹簧云依赖项 Hoxton.SR4