在RPC外部调用,如果网络不稳定的情况下,重试功能是比较重要的必备项。
解决方案例如:
- 根据失败重试时间,创建延迟队列,如果请求失败,入队列,消费,
- spring retry,
- guava retrying,
- sisyphus
本文使用最简单的方式springboot+spring retry,其他的阔以自己去看看
spring retry实现
- 首先导入相关pom依赖
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
- 启动类上加上@EnableRetry
- 基于相关注解使用
@Service
public class LocalWfExampleService {
@Autowired
private WorkflowExampleService workflowExampleServiceRpc;
@Autowired
private WorkflowTask workflowTask;
@Retryable(value= {RemoteAccessException.class},maxAttempts = 3,backoff = @Backoff(delay = 1000l,multiplier = 1))
public void doWfExample(WorkflowExampleDto workflowExampleDto) throws Exception {
List<WorkFlowExample> list= workflowExampleServiceRpc.getWfExample(workflowExampleDto);
if(CollectionUtils.isBlank(list)){
throw new RemoteAccessException("RPC调用无数据");
}
workflowTask.createFlow(list);
}
@Recover
public void recover(RemoteAccessException e) {
log.err(e.getMessage());
}
}
- 测试
@Test
public void test() throw Exception{
localWfExampleService.doWfExample(new WorkflowExampleDto(1,2,3));
}
参数说明
value:抛出指定异常才会重试
include:和value一样,默认为空,当exclude也为空时,默认所以异常
exclude:指定不处理的异常
maxAttempts:最大重试次数,默认3次
backoff:重试等待策略,默认使用@Backoff,@Backoff的value默认为1000L,我们设置为其他;multiplier(指定延迟倍数) 默认为0,表示固定暂停1秒后进行重试,如果把multiplier设置为1,则第一次重试为1秒,第二次为2秒,第三次为3秒。