服务治理-Resilience4j(限流)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了服务治理-Resilience4j(限流)相关的知识,希望对你有一定的参考价值。

Bulkhead

Bulkhead一般用于服务调用客户端,用于限定对特定的服务的并发请求数量,起到一下作用:
1、防?下游依赖被并发请求冲击
2、防?发?连环故障

1、配置规则“order”

//允许最大的并发数量
resilience4j.bulkhead.backends.order.max-concurrent-call=1
//阻塞线程的最大时间量
resilience4j.bulkhead.backends.order.max-wait-time=5

2、注解方式使用

@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;
    }

3、使用配置注册方式

        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

RateLimiter用于限制特定时间段内的执?次数,一般用于服务提供方,保护自己不受到冲击。

1、配置限流策略-“order”

//一个限制周期内可访问次数
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

2、使用注解方式

@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);
    }

3、使用配置注册方式

    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;
    }

以上是关于服务治理-Resilience4j(限流)的主要内容,如果未能解决你的问题,请参考以下文章

Resilience4j 源码解析:限流模块 RateLimiter 与 常见限流算法

Resilience4j 源码解析:限流模块 RateLimiter 与 常见限流算法

微服务治理之降级&限流&熔断

深入浅出SpringCloud原理及实战「Resilience4j入门指南」针对于限流熔断组件Resilience4j的轻量级熔断框架的入门指南

Spring Cloud Resilience4j 断路器

服务治理:高可用的三大利器熔断限流降级