Guava Retry
依赖:
<dependency> <groupId>com.github.rholder</groupId> <artifactId>guava-retrying</artifactId> <version>2.0.0</version> </dependency>
示例:
import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomUtils; import org.springframework.remoting.RemoteAccessException; @Slf4j public class RetryDemoTask { /** * 重试方法 * @return */ public static boolean retryTask(String param) { log.info("收到请求参数:{}",param); int i = RandomUtils.nextInt(0,11); log.info("随机生成的数:{}",i); if (i < 2) { log.info("<2,抛出参数异常."); throw new IllegalArgumentException("参数异常"); }else if (i < 5){ log.info("<5,返回true."); return true; }else if (i < 7){ log.info("<7,返回false."); return false; }else{ //为其他 log.info("else,抛出自定义异常."); throw new RemoteAccessException("else,抛出自定义异常"); } } }
import com.github.rholder.retry.Retryer; import com.github.rholder.retry.RetryerBuilder; import com.github.rholder.retry.StopStrategies; import com.github.rholder.retry.WaitStrategies; import com.xc.xcspringboot.test.Retry.RetryDemoTask; import org.junit.Test; import org.springframework.remoting.RemoteAccessException; import java.util.concurrent.TimeUnit; public class GuavaRetryTest { @Test public void fun01() { // RetryerBuilder 构建重试实例 retryer,可以设置重试源且可以支持多个重试源,可以配置重试次数或重试超时时间,以及可以配置等待时间间隔 Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder() .retryIfExceptionOfType(RemoteAccessException.class)//设置异常重试源 .retryIfResult(res -> res != null && !res) //设置根据结果重试 .withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS)) //设置等待间隔时间 .withStopStrategy(StopStrategies.stopAfterAttempt(3)) //设置最大重试次数 .build(); try { retryer.call(() -> RetryDemoTask.retryTask("abc")); } catch (Exception e) { e.printStackTrace(); } } }
分类:
Java 组件
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2020-07-15 Shell排序
2019-07-15 Spring Cloud Hystrix Dashboard的使用 5.1.3
2019-07-15 Spring Cloud Hystrix 服务容错保护 5.1