Spring 启动 @Retryable 在服务中不工作 class

Spring boot @Retryable not working in service class

我正在尝试在我的应用程序中添加重试逻辑以通过 rest 控制器向各个用户发送邮件,并且我在我的 SpringbootApplication class 文件

中注释了 @EnableRetry
@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 时,每当服务出现异常时 class 它会成功重试 3 次,但在达到最大尝试次数后,我将控制台打印为以下

--> mail service calling
--> mail service calling
--> mail service calling
--> rest failed

而不是打印 --> service failed 我做错了什么..?

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

所以应该是

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

   return false;
}

Java文档:

A suitable recovery handler has a first parameter of type Throwable (or a subtype of Throwable) and a return value of the same type as the @Retryable method to recover from.