Bulkhead通常用於服務調用客戶端,用於限定對特定的服務的併發請求數量,起到一下做用:
一、防⽌下游依賴被併發請求衝擊
二、防⽌發⽣連環故障java
//容許最大的併發數量
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用於限制特定時間段內的執⾏次數,通常用於服務提供方,保護本身不受到衝擊。git
//一個限制週期內可訪問次數 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; }