如何在 Java 中响应 return 时实现异步行为以响应发送电子邮件

How to implement Async behaviour in response to send email while response return in Java

我正在使用 spring 应用程序,我们有一个基于 REST API 的 SOA 架构。我有一个 API 例如 create user(http://myapp/api/createUser)

所以现在当创建用户时我们需要向用户发送一封电子邮件 away.I 确实实现了它但是它等待电子邮件方法发​​送电子邮件并且 return success/failure,这会消耗时间。

请问如何通过在线程中启动电子邮件部分并在后台启动 运行 并向用户发送邮件来立即从 API 获得 return 成功响应。或者如果失败则登录数据库。

请向我推荐 API 或我不想实现 Rabbit MQ 或 Active Queue 之类的消息队列的框架。 请分享那些不会通过生成线程在实时生产服务器中造成问题的实现。

在您的电子邮件发送方法中使用@Async。

参考:http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/Async.html

示例:

@Async
public void sendNotificaitoin(User user) throws MailException {     
    javaMailSender.send(mail);
}

要启用@Async,请在您的配置中使用@EnableAsync。

@SpringBootApplication
@EnableAsync
public class SendingEmailAsyncApplication {     
    public static void main(String[] args) {
        SpringApplication.run(SendingEmailAsyncApplication.class, args);
    }
}

像下面这样使用它:

        @RequestMapping("/signup-success")
        public String signupSuccess(){

            // create user 
            User user = new User();
            user.setFirstName("Dan");
            user.setLastName("Vega");
            user.setEmailAddress("dan@clecares.org");

            // send a notification
            try {
                notificationService.sendNotificaitoin(user);
            }catch( Exception e ){
                // catch error
                logger.info("Error Sending Email: " + e.getMessage());
            }

            return "Thank you for registering with us.";
        }