今天去tolkenview去采集数据,期间使用restTemplate.getForObject 获取相应的数据,但是遇到了链接时间太长的问题。
所以需求就是时间太长,自动重新链接
简而言之,retryTemplate可以完成重试的操作
直接copy使用(心急版)使用的是Springboot框架,lombok
1、在启动类里面,对retryTemplate进行设置注入
@EnableAsync
@Configuration
@SpringBootApplication
@EnableScheduling
public class xxxxApplication {
public static void main(String[] args) {
SpringApplication.run(xxxxApplication.class, args);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
// 创建用于重试的retryTemplate
@Bean
public RetryTemplate retryTemplate() {
RetryTemplate retryTemplate = new RetryTemplate();
//新建RetryPolicy 也就是判断是否重新执行的机制
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
// 一直重新执行 4次
retryPolicy.setMaxAttempts(4);//配置的重试次数
retryTemplate.setRetryPolicy(retryPolicy);
// 新建BackOffPolicy机制 也就是重新执行时的相关设置
ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();
//执行操作的时间间隔
exponentialBackOffPolicy.setInitialInterval(2 * 1000);
// 分别设置指数增长的倍数 则 四次分别为 2,8,512,……
exponentialBackOffPolicy.setMultiplier(2);
// 最大的间隔时间 为40秒
exponentialBackOffPolicy.setMaxInterval(40 * 1000);
retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);
return retryTemplate;
}
}
2、在项目里进行注入,并使用
//分别注入
@Autowired
private RestTemplate restTemplate;
@Autowired
private RetryTemplate retryTemplate;
void getTotalAdress() {
//最终进行连接的url
String finalGetblockdateurl = "^………………………………";
btcBlockList forObject = null;
try {
forObject = retryTemplate.execute(new RetryCallback() {
@Override
public btcBlockList doWithRetry(RetryContext retryContext) throws Throwable {
// 正常需要执行的代码,可以进行重试
return restTemplate.getForObject(finalGetblockdateurl, btcBlockList.class);
}
}, new RecoveryCallback() {
@Override
public btcBlockList recover(RetryContext retryContext) throws Exception {
System.out.println("超时啦!");
//当重复执行次数超过后,需要执行的操作
return null;
}
});
} catch (Throwable e) {
e.printStackTrace();
}
}
原理理解:这方面其实我也不太懂,推荐一个博主的链接
利用Spring-Retry定制化你的RPC重试
从里面借用一张图,也就是说
上面两张图都是链接内的,大家可以进行查看。



