如果在开发中遇到需要发送邮件的任务之类的话,为了不影响用户的体验,我们就可以在后台开启一个线程去执行,然后把结果先返回给用户。
如何开启一个线程。springboot已经给我们封装好了,只需要加上一个注解就可以了。
在控制层中注入,然后调用服务层的方法即可。
控制层代码:
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String hello(){
asyncService.hello();
return "OK";
}
然后在服务层的方法上面加上以下注解就可以了。
@Async
最后,就是在springboot的启动类开启多线程。加上注解
@EnableAsync
springboot已经有了封装好的方法,直接用就可以了
在需要定时的方法中加入注解Scheduled
,传入cron
就可以了。不知道cron是什么的百度一下就明白了
@Scheduled(cron = "0 22 22 * * ?")
然后一样在启动类加上注解
@EnableScheduling
就可以了!
- springboot发送邮件
使用springboot发送邮件需要导入start的包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
JavaMailSender
是springboot已经封装好的,我们只需要做简单的操作就可以了,记得自动注入
@Autowired
JavaMailSender mailSender;
void contextLoads() {
//一个简单的邮件
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("关于邮件发送");//设置主题
mailMessage.setText("这是测试邮件发送");//设置内容
mailMessage.setTo("xxxx@qq.com");//发送给谁
mailMessage.setFrom("xxxx@qq.com");//从哪里发送出去
mailSender.send(mailMessage);
}
void contextLoads2() throws MessagingException {
//一个复杂的邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
//组装
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject("关于复杂邮件发送++");
helper.setText("<p style='color:red'>这是测试复杂邮件发送</p>",true);
//添加附件
helper.addAttachment("1.jpg", new File("C:\\Users\\nanth\\Pictures\\Saved Pictures\\01.jpg"));
helper.setTo("xxxx@qq.com");
helper.setFrom("xxxx@qq.com");
mailSender.send(mimeMessage);
}