Resilience4j是一个轻量级的容错组件,其灵感来自于Hystrix,但主要为Java8和函数式编程所设计。轻量级体现在其只用Vavr库(前身是Javaslang),没有任何外部依赖。而Hystrix依赖了Archaius,Archaius本身又依赖很多第三方包,例如Guava、ApacheCommonsConfiguration等。
限速组件架构:
Resilience4j提供了如下几款核心组件
resilience4j-circuitbreaker:Circuitbreaking
resilience4j-ratelimiter:Ratelimiting
resilience4j-bulkhead:Bulkheading
resilience4j-retry:Automaticretrying(syncandasync)
resilience4j-cache:Responsecaching
附件组件包括:
resilience4j-reactor:SpringReactoradapter
resilience4j-rxjava2:RxJava2adapter
resilience4j-micrometer:MicrometerMetricsexporter
resilience4j-metrics:DropwizardMetricsexporter
resilience4j-prometheus:PrometheusMetricsexporter
resilience4j-spring-boot:SpringBootStarter
resilience4j-ratpack:RatpackStarter
resilience4j-retrofit:RetrofitCallAdapterFactories
resilience4j-vertx:VertxFuturedecorator
resilience4j-consumer:CircularBufferEventconsumer
使用示例:
CircuitBreaker,RetryandFallback
RateLimiter
Bulkhead
Cache
Metrics
Consumeemittedevents
使用Resilience4j实现请求调用频率限制的示例代码:
// Create a custom RateLimiter configurationRateLimiterConfig config = RateLimiterConfig.custom() .timeoutDuration(Duration.ofMillis(100)) .limitRefreshPeriod(Duration.ofSeconds(1)) .limitForPeriod(1) .build();// Create a RateLimiterRateLimiter rateLimiter = RateLimiter.of("backendName", config);// Decorate your call to BackendService.doSomething()Supplier<String> restrictedSupplier = RateLimiter .decorateSupplier(rateLimiter, backendService::doSomething);// First call is successfulTry<String> firstTry = Try.ofSupplier(restrictedSupplier);assertThat(firstTry.isSuccess()).isTrue();// Second call fails, because the call was not permittedTry<String> secondTry = Try.of(restrictedSupplier);assertThat(secondTry.isFailure()).isTrue();assertThat(secondTry.getCause()).isInstanceOf(RequestNotPermitted.class);
评论