Resilience4j轻量级的容错组件

联合创作 · 2023-09-28 11:37

Resilience4j 是一个轻量级的容错组件,其灵感来自于 Hystrix,但主要为 Java 8 和函数式编程所设计。轻量级体现在其只用 Vavr 库(前身是 Javaslang),没有任何外部依赖。而 Hystrix 依赖了 Archaius ,Archaius 本身又依赖很多第三方包,例如 Guava、Apache Commons Configuration 等。

限速组件架构:

Resilience4j 提供了如下几款核心组件

  • resilience4j-circuitbreaker: Circuit breaking

  • resilience4j-ratelimiter: Rate limiting

  • resilience4j-bulkhead: Bulkheading

  • resilience4j-retry: Automatic retrying (sync and async)

  • resilience4j-cache: Response caching

附件组件包括:

  • resilience4j-reactor: Spring Reactor adapter

  • resilience4j-rxjava2: RxJava2 adapter

  • resilience4j-micrometer: Micrometer Metrics exporter

  • resilience4j-metrics: Dropwizard Metrics exporter

  • resilience4j-prometheus: Prometheus Metrics exporter

  • resilience4j-spring-boot: Spring Boot Starter

  • resilience4j-ratpack: Ratpack Starter

  • resilience4j-retrofit: Retrofit Call Adapter Factories

  • resilience4j-vertx: Vertx Future decorator

  • resilience4j-consumer: Circular Buffer Event consumer

使用示例:

使用 Resilience4j 实现请求调用频率限制的示例代码:

// Create a custom RateLimiter configuration
RateLimiterConfig config = RateLimiterConfig.custom()
    .timeoutDuration(Duration.ofMillis(100))
    .limitRefreshPeriod(Duration.ofSeconds(1))
    .limitForPeriod(1)
    .build();
// Create a RateLimiter
RateLimiter rateLimiter = RateLimiter.of("backendName", config);

// Decorate your call to BackendService.doSomething()
Supplier<String> restrictedSupplier = RateLimiter
    .decorateSupplier(rateLimiter, backendService::doSomething);

// First call is successful
Try<String> firstTry = Try.ofSupplier(restrictedSupplier);
assertThat(firstTry.isSuccess()).isTrue();

// Second call fails, because the call was not permitted
Try<String> secondTry = Try.of(restrictedSupplier);
assertThat(secondTry.isFailure()).isTrue();
assertThat(secondTry.getCause()).isInstanceOf(RequestNotPermitted.class);
浏览 9
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报