当前位置: 首页 > 工具软件 > failsafe > 使用案例 >

java库的使用--Failsafe

阚允晨
2023-12-01

介绍

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

参考

https://failsafe.dev/

 类似资料: