【Java】Retryer重试机制

背景:

项目一个htmlunit自动化测试框架里,针对webclient.getPage(url)缺失异常处理,导致程序异常退出。

考虑异常抛出是由于另一个web服务端尚未完全启动完毕,从而导致http连接失效所致。

可以加入异常重试机制:如果出现异常,设定重试次数,等待web服务端启动完成,从而增加程序成功率。

参考:

https://www.icode9.com/content-4-546143.html

https://blog.csdn.net/aitangyong/article/details/53894997

https://segmentfault.com/a/1190000014482325

https://blog.csdn.net/gurong168/article/details/53081385?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromBaidu-1.control&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromBaidu-1.control

RetryerBuilder

RetryerBuilder 是一个 factory 创建者,可以定制设置重试源且可以支持多个重试源,可以配置重试次数或重试超时时间,以及可以配置等待时间间隔,创建重试者 Retryer 实例。

RetryerBuilder 的重试源支持 Exception 异常对象和自定义断言对象,通过retryIfException 和 retryIfResult 设置,同时支持多个且能兼容。

  • retryIfException

retryIfException,抛出 runtime 异常、checked 异常时都会重试,但是抛出 error 不会重试。

  • retryIfRuntimeException

retryIfRuntimeException 只会在抛 runtime 异常的时候才重试,checked 异常和error 都不重试。

  • retryIfExceptionOfType

retryIfExceptionOfType 允许我们只在发生特定异常的时候才重试,比如NullPointerException 和 IllegalStateException 都属于 runtime 异常,也包括自定义的error。

原文地址:https://www.cnblogs.com/cathygx/p/14049779.html