首页 > 解决方案 > 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 我做错了什么..?

标签: spring-bootspring-retry

解决方案


根据 Javadoc,@Recover您的恢复方法必须具有与 Retryable 方法相同的返回类型。

所以应该是

@Recover
public boolean recover(Exception ex) {
   System.out.println("--> service failed");

   return false;
}

Java文档:

合适的恢复处理程序具有 Throwable 类型(或 Throwable 的子类型)的第一个参数和与@Retryable要从中恢复的方法相同类型的返回值。


推荐阅读