在我的项目中,我需要在注册后发送电子邮件以激活帐户。还需要在某些事件上发送其他电子邮件。任何人都可以帮助我如何异步实现这一点。我是否需要在应用程序中发送电子邮件的方法上使用@Async,或者我需要创建一些从应用程序组件接收jms消息并发送电子邮件的JMS组件。请建议我如何解决这个问题。
此致
答案 0 :(得分:0)
为电子邮件发件人编写服务类,并在触发电子邮件的邮件上添加@Async注释。
假设您的组件正在触发电子邮件
@Controller
public class OrderController {
@Autowired
private MailSenderUtilityService mailSenderUtilityService;
@RequestMapping("/setShippingAddress")
private String sendAnEmail(Model model, Order order, User user){
..... Your code goes here .....
mailSenderUtilityService.sendYourEmail(Order order, User user, Locale english);
return "emailSent";
}
}
@Service
public class MailSenderUtilityService {
@Autowired
private JavaMailSender mailSender;
@Autowired
private MailConstructor mailContructor;
@Async
public void sendOrderSubmittedEmail(Order order, User user, Locale english) {
CompletableFuture<MimeMessagePreparator> email = mailContructor.constructSimpleOrderPlacedEmail(order, user, Locale.ENGLISH);
try {
System.out.println("********************* SLEEPING NOW FOR TESTING PURPOSE **********************");
Thread.sleep(60000);
mailSender.send(email.get());
} catch (MailException | InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Component
public class MailConstructor {
@Autowired
private Environment env;
@Autowired
private TemplateEngine templateEngine;
@Async
public CompletableFuture<MimeMessagePreparator> constructSimpleOrderPlacedEmail(Order order, User user, Locale locale) {
Context context = new Context();
context.setVariable("order", order);
context.setVariable("user", user);
context.setVariable("cartItemList", order.getCartItemList());
String text = templateEngine.process("orderConfirmationEmailTemplate", context);
MimeMessagePreparator messagePreparator = new MimeMessagePreparator() {
@Override
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper email = new MimeMessageHelper(mimeMessage);
email.setTo(user.getEmail());
email.setFrom(new InternetAddress("abhibookstore123@gmail.com"));
email.setSubject("Order Confirmation - "+ order.getId());
email.setText(text, true);
}
};
return CompletableFuture.completedFuture(messagePreparator);
}
这将以异步方式触发您的电子邮件。在发送电子邮件之前,它不会等待60秒。
控制器中的代码执行将继续,60秒后将触发电子邮件。
在这里,您可以找到完整的示例 - here
答案 1 :(得分:0)
除了@Abhinavece的答案,您还必须在应用程序中启用Async
@SpringBootApplication
**@EnableAsync**
public class SpringPrimeFacesApplication {
public static void main(String[] args) {
SpringApplication.run(SpringPrimeFacesApplication.class, args);
}
@Bean
SessionRegistry sessionRegistry() {
return new SessionRegistryImpl();
}
@Bean
public ActiveUserStore activeUserStore(){
return new ActiveUserStore();
}
}