您好,登錄后才能下訂單哦!
Bulkhead一般用于服務調用客戶端,用于限定對特定的服務的并發請求數量,起到一下作用:
1、防?下游依賴被并發請求沖擊
2、防?發?連環故障
//允許最大的并發數量
resilience4j.bulkhead.backends.order.max-concurrent-call=1
//阻塞線程的最大時間量
resilience4j.bulkhead.backends.order.max-wait-time=5
@PostMapping("/order")
@io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker(name = "order")
@io.github.resilience4j.bulkhead.annotation.Bulkhead(name = "order")
public CoffeeOrder createOrder() {
NewOrderRequest orderRequest = NewOrderRequest.builder()
.customer("Li Lei")
.items(Arrays.asList("capuccino"))
.build();
CoffeeOrder order = coffeeOrderService.create(orderRequest);
log.info("Order ID: {}", order != null ? order.getId() : "-");
return order;
}
private CircuitBreaker circuitBreaker;
private Bulkhead bulkhead;
//構造方法
public CustomerController(CircuitBreakerRegistry circuitBreakerRegistry,
BulkheadRegistry bulkheadRegistry) {
circuitBreaker = circuitBreakerRegistry.circuitBreaker("order");
bulkhead = bulkheadRegistry.bulkhead("order");
}
@GetMapping("/menu")
public List<Coffee> readMenu() {
return Try.ofSupplier(
Bulkhead.decorateSupplier(bulkhead,
CircuitBreaker.decorateSupplier(circuitBreaker,
() -> coffeeService.getAll())))
.recover(CircuitBreakerOpenException.class, Collections.emptyList())
.recover(BulkheadFullException.class, Collections.emptyList())
.get();
}
RateLimiter用于限制特定時間段內的執?次數,一般用于服務提供方,保護自己不受到沖擊。
//一個限制周期內可訪問次數
resilience4j.ratelimiter.limiters.order.limit-for-period=3
//限制周期,每個周期之后,速率限制器將重置回limitForPeriod值
resilience4j.ratelimiter.limiters.order.limit-refresh-period-in-millis=30000
//線程等待允許執行時間
resilience4j.ratelimiter.limiters.order.timeout-in-millis=1000
//開啟時間訂閱
resilience4j.ratelimiter.limiters.order.subscribe-for-events=true
//開啟監控監控
resilience4j.ratelimiter.limiters.order.register-health-indicator=true
@PostMapping(path = "/", consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseStatus(HttpStatus.CREATED)
@io.github.resilience4j.ratelimiter.annotation.RateLimiter(name = "order")
public CoffeeOrder create(@RequestBody NewOrderRequest newOrder) {
log.info("Receive new Order {}", newOrder);
Coffee[] coffeeList = coffeeService.getCoffeeByName(newOrder.getItems())
.toArray(new Coffee[]{});
return orderService.createOrder(newOrder.getCustomer(), coffeeList);
}
private RateLimiter rateLimiter;
//構造方法
public CoffeeOrderController(RateLimiterRegistry rateLimiterRegistry) {
rateLimiter = rateLimiterRegistry.rateLimiter("order");
}
@GetMapping("/{id}")
public CoffeeOrder getOrder(@PathVariable("id") Long id) {
CoffeeOrder order = null;
try {
order = rateLimiter.executeSupplier(() -> orderService.get(id));
log.info("Get Order: {}", order);
} catch (RequestNotPermitted e) {
log.warn("Request Not Permitted! {}", e.getMessage());
}
return order;
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。