如何在Spring Boot中处理@Async。

huangapple 未分类评论50阅读模式
英文:

How to handle @Async in Spring boot

问题

public class ServiceImpl {

    @Autowired
    EmailService emailService;

    public void arr() throws Exception {
        int[] arr = {1, 2, 3, 4};
        for (int i = 0; i < arr.length + 1; i++) {
            System.out.print(i + " ");
        }
        emailService.sendMail("邮件主题", "邮件正文", "xuz@gmail.com", "abc@gmail.com");
    }
}

@EnableAsync
public class EmailService {
    @Async
    public void sendMail(String subject, String body, String from, String to) {
        // 发送邮件功能的实现
    }
}

我在邮件服务中使用了 @Async 注解来触发邮件发送。如果在调用方法中发生任何错误,邮件会被触发,而不考虑调用方法中的任何异常。

我不希望在调用方法发生错误后继续执行邮件发送方法。我该如何处理?

在上面的示例中,for 循环会抛出 ArrayIndexOutOfBoundException,即使出现异常,邮件也会被触发,因为它是一个异步函数。
我不希望在 arr() 方法中出现异常时触发邮件发送。

英文:
public class ServiceImpl{
    
    @Autowired
    EmailService emailService;
    
    public void arr() throws Exception
    {
        int[] arr={1,2,3,4};
        for(int i=0;i&lt;arr.length+1;i++)
        {
            System.out.print(i+&quot; &quot;);
        }
        emailService.sendMail(&quot;Subject of mail&quot;,&quot;body of mail&quot;,&quot;xuz@gmail.com&quot;,&quot;abc@gmail.com&quot;);
    }
}
    
    
@EnableAsync
public class EmailService {
    @Async
    public void sendMail(String subject,String body,String from,String to)
    {
        //Implementation of sendMail function
    }
}

I have used @Async annotation in the email service for triggering the mail, if any error occurs in the caller method the mail is getting triggered irrespective of any exceptions in the caller method.

I don't want the email method to get executed after the error occurs in the caller method. how can i handle this?

In the above example the for loop throws arrayIndexOutOfBoundException even after the exception occurs the mail will get triggered since it is a async function .
I don't want the mail to get triggered if exception occurs in arr() method

huangapple
  • 本文由 发表于 2020年5月5日 09:58:41
  • 转载请务必保留本文链接:https://java.coder-hub.com/61604489.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定