Reputation: 1069
I'm trying to add retry logic in my application for sending mail to respective users through rest controller and i have annotate @EnableRetry
in my SpringbootApplication class file
@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");
}
}
My 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");
}
}
When i try to run the /sendMail
and whenever exception arise in service class it retrying 3 times successfully but after reaching the maxattempts, i'm getting the console print as below
--> mail service calling
--> mail service calling
--> mail service calling
--> rest failed
instead of printing
--> service failed
Here what im doing wrong..?
Upvotes: 0
Views: 4210
Reputation: 1560
As per Javadoc for @Recover
your recover method must have the same return type as the Retryable method.
So it should be
@Recover
public boolean recover(Exception ex) {
System.out.println("--> service failed");
return false;
}
JavaDoc:
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.
Upvotes: 4