Guava-Retry组件
基于guava的重试组件,这款组件的功能相比于Spring要更加完善和丰富,但是在接入到Spring当中可能会对代码造成一定的侵入性:
首先是引入相关的依赖配置:
<dependency> <groupId>com.github.rholder</groupId> <artifactId>guava-retrying</artifactId> <version>2.0.0</version> </dependency> 复制代码
然后是具体的使用累代码:
package org.idea.qiyu.framework.retry.guava; import com.github.rholder.retry.*; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; /** * @Author linhao * @Date created in 9:18 上午 2021/10/4 */ public class Application { static class ResponseInfo { int code; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public ResponseInfo() { } public static ResponseInfo buildSuccess(){ ResponseInfo responseInfo = new ResponseInfo(); responseInfo.setCode(1); return responseInfo; } } public static void main(String[] args) throws ExecutionException, RetryException { Callable<ResponseInfo> callable = new Callable<ResponseInfo>() { @Override public ResponseInfo call() throws Exception { System.out.println("call ..."); return ResponseInfo.buildSuccess(); } }; Retryer<ResponseInfo> retryer = RetryerBuilder.<ResponseInfo>newBuilder() .retryIfResult(expectResult-> expectResult.getCode()==1) .retryIfException() .withStopStrategy(StopStrategies.stopAfterAttempt(3)) .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS)) .withRetryListener(new MyRetryListener()) .build(); retryer.call(callable); } } 复制代码
监听器部分代码:
package org.idea.qiyu.framework.retry.guava; import com.github.rholder.retry.Attempt; import com.github.rholder.retry.RetryListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @Author linhao * @Date created in 9:35 上午 2021/10/4 */ public class MyRetryListener implements RetryListener { private static final Logger LOGGER = LoggerFactory.getLogger(MyRetryListener.class); @Override public <V> void onRetry(Attempt<V> attempt) { // 第几次重试(注意:第一次重试其实是第一次调用) System.out.printf("retry time : %s \n", attempt.getAttemptNumber()); // 距离第一次重试的延迟 System.out.printf("retry delay : %s \n", attempt.getDelaySinceFirstAttempt()); // 是否因异常终止 if (attempt.hasException()) { System.out.printf("causeBy: %s \n", attempt.getExceptionCause()); } // 正常返回时的结果 if (attempt.hasResult()) { System.out.printf("result=%s \n", attempt.getResult()); } } } 复制代码
这段代码中的retryIfResult是我比较喜欢的一个功能,可以根据自定义的返回尸体对象来决定是否后续需要执行重试的操作,感觉相比于Spring组件会更加灵活。
和Spring的Retry组件相比,它也是支持重试终止策略,重试间隔策略,重试监听器这些配置项的定义。