添加依赖
<!--重试-->
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<!-- <version>1.2.4.RELEASE</version>-->
</dependency>
配置类
package com.bsk.demo.config;
import cn.com.infosec.netsign.agent.exception.NetSignAgentException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.support.RetryTemplate;
/**
* @Author yangquan
* @Date 2023/3/8 16:53
*/
@Configuration
public class RetryTemplateConfiguration {
/**
* RetryTemplate对象
*
* @return 重试模板
*/
@Bean
public RetryTemplate gainRetryTemplate() {
//添加依赖不要加版本号
// <dependency>
// <groupId>org.springframework.retry</groupId>
// <artifactId>spring-retry</artifactId>
// <!-- <version>1.2.4.RELEASE</version> -->
// </dependency>
return RetryTemplate.builder()
//重连4次
.maxAttempts(4)
.retryOn(Exception.class)
.retryOn(NetSignAgentException.class)
.traversingCauses()
.build();
}
}
代码
package com.bsk.demo.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 重试
*
* @Author yangquan
* @Date 2023/3/8 15:44
*/
@Slf4j
@RestController
public class RetryTemplateController {
@Autowired
private RetryTemplate retryTemplate;
@RequestMapping("retryTemplate")
public Boolean test() {
try {
Boolean rtnBool = retryTemplate.execute(retryContext -> {
int turn = retryContext.getRetryCount();
// if (turn > 0)
log.info(">>>>>>>>>>>>>>>>>>【下载信用报告】第" + turn + "次重试<<<<<<<<<<<<<<<<<<<<<<<<<<");
getName();
return true;
}, recoverContext -> {
log.info(">>>>>>>>>>>>>>>>>>【下载信用报告】重试次数达到最大<<<<<<<<<<<<<<<<<<<<<<<<<<<<", recoverContext.getLastThrowable());
return false;
});
if(rtnBool){
return true;
}
return false;
} catch (RuntimeException e) {
e.printStackTrace();
}
return false;
}
public String getName() {
throw new RuntimeException();
// return "1";
}
}
这辈子坚持与不坚持都不可怕,怕的是独自走在坚持的道路上!!!