Failsafe 是一个轻量级的零依赖库,用于处理 Java 8+ 中的故障。
<!-- https://mvnrepository.com/artifact/net.jodah/failsafe -->
<dependency>
<groupId>net.jodah</groupId>
<artifactId>failsafe</artifactId>
<version>2.4.4</version>
</dependency>
策略包括retry(重试), circuit breaker(断路器), rate limiter(速率限制器), timeout(超时), bulkhead, fallback(回调)
RetryPolicy<Object> retryPolicy = RetryPolicy.builder()
.handle(ConnectException.class)
.withDelay(Duration.ofSeconds(1))
.withMaxRetries(3)
.build();
或
RetryPolicy<Object> retryPolicy = new RetryPolicy<>()
.handle(Exception.class)
.withDelay(Duration.ofSeconds(10))
.withMaxRetries(10)
.onFailedAttempt(e -> log.error("Fail to create kafka producer.", e.getLastFailure()))
.onRetry(e -> log.warn("Failure #{}: trying again.", e.getAttemptCount()));
Failsafe.with(fallback)
.compose(retryPolicy)
.compose(circuitBreaker)
.compose(timeout)
.get(supplier);
或
Failsafe.with(fallback, retryPolicy, circuitBreaker, timeout).get(supplier);
run方法
Failsafe.with(retryPolicy).run(() -> connect());
get方法
Connection connection = Failsafe.with(retryPolicy).get(() -> connect());
runAysnc方法
CompletableFuture<Void> future = Failsafe.with(retryPolicy).runAsync(() -> connect());
getAsync方法
CompletableFuture<Connection> future = Failsafe.with(retryPolicy).getAsync(() -> connect());
Failsafe.with(retryPolicy, circuitBreaker)
.onSuccess(e -> log.info("Connected to {}", e.getResult()))
.onFailure(e -> log.error("Failed to create connection", e.getException()))
.get(this::connect);
取消同步执行
Call<Connection> call = Failsafe.with(retryPolicy).newCall(this::connect);
scheduler.schedule(() -> call.cancel(false), 10, TimeUnit.SECONDS);
Connection connection = call.execute();
取消异步执行
CompletableFuture<Connection> future = Failsafe.with(retryPolicy).getAsync(this::connect);
future.cancel(shouldInterrupt);