spring-boot - Spring boot @Retryable 在服务类中不起作用
问题描述
我正在尝试在我的应用程序中添加重试逻辑,以便通过休息控制器向各个用户发送邮件,并且我@EnableRetry
在 SpringbootApplication 类文件中进行了注释
@RestController
public class TserviceController {
@Autowired
private Tservice tService ;
@RequestMapping(method = RequestMethod.GET, value = "/sendMail")
public Object sayHello(HttpServletResponse response) throws IOException {
try{
boolean t = tService.sendConfirmationMail();
}catch(Exception e){
System.out.println("--> rest failed");
return ResponseEntity.status(500).body("error");
}
return ResponseEntity.status(200).body("success");
}
}
我的Tservice.class
@Service
public class Tservice {
private JavaMailSender javaMailSender;
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
public Tservice(JavaMailSender javaMailSender) {
this.javaMailSender = javaMailSender;
}
@Retryable(backoff = @Backoff(delay = 5000), maxAttempts = 3)
public boolean sendConfirmationMail() throws Exception {
try{
System.out.println("--> mail service calling");
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setTo(toEmail);
mailMessage.setSubject(subject);
mailMessage.setText(message);
mailMessage.setFrom(emailFrom);
javaMailSender.send(mailMessage);
return true;
}catch(Exception e){
throw new Exception(e);
}
}
@Recover
public void recover(Exception ex) {
System.out.println("--> service failed");
}
}
当我尝试运行时/sendMail
,每当服务类中出现异常时,它会成功重试 3 次,但在达到最大尝试次数后,我得到的控制台打印如下
--> mail service calling
--> mail service calling
--> mail service calling
--> rest failed
而不是在这里打印
--> service failed
我做错了什么..?
解决方案
根据 Javadoc,@Recover
您的恢复方法必须具有与 Retryable 方法相同的返回类型。
所以应该是
@Recover
public boolean recover(Exception ex) {
System.out.println("--> service failed");
return false;
}
Java文档:
合适的恢复处理程序具有 Throwable 类型(或 Throwable 的子类型)的第一个参数和与
@Retryable
要从中恢复的方法相同类型的返回值。
推荐阅读
- python - 在 Python 中将序列拆分为单个步骤的最优雅方法
- r - 在 R 中的地图上显示时间序列预测的预测区间(空间建模)
- c# - Firebase RealTime DB - 查询返回旧的 DataSnapshot - 而不是新键,除非重新启动应用程序
- c# - Specflow 允许可为空的表参数
- python - 为什么我的 Flask API 端点出现 CORS 错误,而其他类似编程的端点却没有?
- nginx - 从 Codepipeline 更新文件后 AWS EC2 站点未更新
- python - 将熊猫数据框插入influxdb的问题
- javascript - flex 框的样式问题,文本走得太远
- css - 如何将这段 CSS 代码转换为 SCCS?
- python - 嵌套的while循环不遍历Python中的列