经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Java » 查看文章
【java框架】SpringBoot(4)--SpringBoot实现异步、邮件、定时任务
来源:cnblogs  作者:人无名,则可专心练剑  时间:2021/3/29 9:19:34  对本文有异议

1.SpringBoot整合任务机制

1.1.SpringBoot实现异步方法

日常开发中涉及很多界面与后端的交互响应,都不是同步的,基于SpringBoot为我们提供了注解方式实现异步方法。使得前端的请求响应与后端的业务逻辑方法实现异步执行。提升了客户的体验。不由得说一句,SpringBoot的封装的确是精妙强大,以前需要多线程、Ajax实现异步,而SpringBoot底层封装之后,两个注解就Over了!

①需要在SpringApplication执行类上开启异步,使用@EnableAsync:

  1. @SpringBootApplication
  2. @EnableAsync //开启异步
  3. public class SpringtestApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(SpringtestApplication.class, args);
  6. }
  7. }

 

②同时在执行调用耗时的方法上加上@Async表示该方法是异步方法:

  1. @Service
  2. public class AsyncService {
  3. @Async
  4. public void execute(){
  5. try {
  6. Thread.sleep(3000); //执行系统耗时任务
  7. } catch (InterruptedException e) {
  8. e.printStackTrace();
  9. }
  10. System.out.println("任务执行成功!");
  11. }
  12. }

 

③那么执行Controller层的调用异步方法时就会异步去执行方法,得到响应“success”返回而同时异步执行后台耗时方法:

  1. @RestController
  2. public class AsyncController {
  3. @Autowired
  4. private AsyncService service;
  5. @RequestMapping("/execute")
  6. public String executeTask(){
  7. service.execute(); //异步执行3s
  8. return "success"; //异步返回结果
  9. }
  10. }

 

1.2.SpringBoot实现邮件发送

Spring Boot中发送邮件具体的使用步骤如下

1、添加Starter模块依赖

2、添加Spring Boot配置(QQ/网易系/Gmail)

3、调用JavaMailSender接口发送邮件

 

①在pom.xml中添加邮件发送starter依赖:

  1. <!--邮件发送-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-mail</artifactId>
  5. </dependency>

 

②对应QQ邮箱发送,去QQ邮箱客户端开启POP3/SMTP服务,获取授权码:

 

③添加配置参数,在application.yml中配置邮箱发送方式:

QQ邮箱:

  1. # QQ邮箱配置
  2. spring:
  3. mail:
  4. host: smtp.qq.com #发送邮件服务器
  5. username: 241667****@qq.com #发送邮件的邮箱地址
  6. password: ************ #客户端授权码,不是邮箱密码,这个在qq邮箱设置里面自动生成的
  7. properties.mail.smtp.port: 465 #端口号465或587
  8. from: 241667****@qq.com # 发送邮件的地址,和上面username一致
  9. protocol: smtps #如果使用端口为465,将protocol的smtp改为smtps;配置文件端口为587,则可以使用smtp。
  10. #开启加密验证
  11. properties.mail.smtp.ssl.enable: true

 

网易邮箱:

  1. ##网易系(126/163/yeah)邮箱配置
  2. spring:
  3. mail:
  4. host: smtp.163.com #发送邮件服务器
  5. username: hyfmail****@163.com #发送邮件的邮箱地址
  6. password: ************ #客户端授权码,不是邮箱密码,网易的是自己设置的
  7. properties.mail.smtp.port: 465 #465或者994
  8. from: hyfmail****@163.com # 发送邮件的地址,和上面username一致
  9. properties.mail.smtp.ssl.enable: true
  10. default-encoding: utf-8

 

④编写邮件发送接口,实现类:

  1. public interface IMailService {
  2. /**
  3. * 发送文本邮件
  4. * @param to 收件人
  5. * @param subject 主题
  6. * @param content 内容
  7. */
  8. void sendSimpleMail(String to, String subject, String content);
  9. /**
  10. * 发送HTML邮件
  11. * @param to 收件人
  12. * @param subject 主题
  13. * @param content 内容
  14. */
  15. public void sendHtmlMail(String to, String subject, String content);
  16. /**
  17. * 发送带附件的邮件
  18. * @param to 收件人
  19. * @param subject 主题
  20. * @param content 内容
  21. * @param filePath 附件
  22. */
  23. public void sendAttachmentsMail(String to, String subject, String content, String filePath);
  24. }

 

  1. @Service
  2. public class MailServiceImpl implements IMailService {
  3. private final Logger logger = LoggerFactory.getLogger(this.getClass());
  4. /**
  5. * Spring Boot 提供了一个发送邮件的简单抽象,使用的是下面这个接口,这里直接注入即可使用
  6. */
  7. @Autowired
  8. private JavaMailSenderImpl mailSender;
  9. /**
  10. * 配置文件中我的qq邮箱
  11. */
  12. @Value("${spring.mail.from}")
  13. private String from;
  14. @Override
  15. public void sendSimpleMail(String to, String subject, String content) {
  16. //创建SimpleMailMessage对象
  17. SimpleMailMessage message = new SimpleMailMessage();
  18. //邮件发送人
  19. message.setFrom(from);
  20. //邮件接收人
  21. message.setTo(to);
  22. //邮件主题
  23. message.setSubject(subject);
  24. //邮件内容
  25. message.setText(content);
  26. //发送邮件
  27. mailSender.send(message);
  28. }
  29. /**
  30. * html邮件
  31. * @param to 收件人
  32. * @param subject 主题
  33. * @param content 内容
  34. */
  35. @Override
  36. public void sendHtmlMail(String to, String subject, String content) {
  37. //获取MimeMessage对象
  38. MimeMessage message = mailSender.createMimeMessage();
  39. MimeMessageHelper messageHelper;
  40. try {
  41. messageHelper = new MimeMessageHelper(message, true);
  42. //邮件发送人
  43. messageHelper.setFrom(from);
  44. //邮件接收人
  45. messageHelper.setTo(to);
  46. //邮件主题
  47. message.setSubject(subject);
  48. //邮件内容,html格式
  49. messageHelper.setText(content, true);
  50. //发送
  51. mailSender.send(message);
  52. //日志信息
  53. logger.info("邮件已经发送。");
  54. } catch (MessagingException e) {
  55. logger.error("发送邮件时发生异常!", e);
  56. }
  57. }
  58. /**
  59. * 带附件的邮件
  60. * @param to 收件人
  61. * @param subject 主题
  62. * @param content 内容
  63. * @param filePath 附件
  64. */
  65. @Override
  66. public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
  67. MimeMessage message = mailSender.createMimeMessage();
  68. try {
  69. MimeMessageHelper helper = new MimeMessageHelper(message, true);
  70. helper.setFrom(from);
  71. helper.setTo(to);
  72. helper.setSubject(subject);
  73. helper.setText(content, true);
  74. FileSystemResource file = new FileSystemResource(new File(filePath));
  75. String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
  76. helper.addAttachment(fileName, file);
  77. mailSender.send(message);
  78. //日志信息
  79. logger.info("邮件已经发送。");
  80. } catch (MessagingException e) {
  81. logger.error("发送邮件时发生异常!", e);
  82. }
  83. }
  84. }

 

⑤编写测试类:

  1. @SpringBootTest(classes = {SendmailApplication.class})
  2. @RunWith(SpringRunner.class)
  3. public class MailAppTest {
  4. @Autowired
  5. private IMailService mailService;
  6. /**
  7. * 测试发送文本邮件
  8. */
  9. @Test
  10. public void testSendMail() {
  11. mailService.sendSimpleMail("hyfmailsave@163.com","主题:你好普通邮件","内容:第一封邮件");
  12. }
  13. /**
  14. * 测试发送Html邮件
  15. */
  16. @Test
  17. public void sendHtmlMail(){
  18. mailService.sendHtmlMail("hyfmailsave@163.com","主题:你好html邮件","<h1>内容:第一封html邮件</h1>");
  19. }
  20. @Test
  21. public void sendMimeContentMail(){
  22. mailService.sendAttachmentsMail("hyfmailsave@163.com", "主题:你好复杂带附件邮件",
  23. "<p style='color:red'>谢谢你的html邮件及问候~</p>", "E:\\Workspaces\\SpringBoot_Study\\springboot_test\\src\\main\\resources\\static\\1.jpg");
  24. }
  25. }

 

1.3.定时任务

SpringBoot中执行定时任务主要用到有两个重要接口与两个任务调度的注解:

  • TaskScheduler    任务调度者
  • TaskExecutor    任务执行者
  • @EnableScheduling    开启定时功能的注解
  • @Scheduled    用于在需要定时执行的方法上,表示在某一时刻定时执行

 

对应注解使用如下:

启动类:

  1. @SpringBootApplication
  2. @EnableAsync //开启异步
  3. @EnableScheduling //开启定时功能的注解
  4. public class SpringtestApplication {
  5. public static void main(String[] args) {
  6. SpringApplication.run(SpringtestApplication.class, args);
  7. }
  8. }

 

启动方法:

  1. @Service
  2. public class ScheduleService {
  3. //定时执行注解@Scheduled,需要使用cron表达式进行定时任务执行
  4. //表示每天下午13:43触发
  5. @Scheduled(cron = "0 43 13 ? * *")
  6. public void timeExecute(){
  7. System.out.println("该任务被触发执行了~~~");
  8. }
  9. }

 

启动SpringBoot项目,SpringBoot则会开启定时任务执行并扫描方法上需要定时执行的注解,去定时执行相关的任务。

 

常用cron表达式如下:

  1. 0 0 2 1 * ? 表示在每月的1日的凌晨2点调整任务
  2. 0 15 10 ? * MON-FRI 表示周一到周五每天上午10:15执行作业
  3. 0 15 10 ? 6L 2002-2006 表示2002-2006年的每个月的最后一个星期五上午10:15执行作
  4. 0 0 10,14,16 * * ? 每天上午10点,下午2点,4
  5. 0 0/30 9-17 * * ? 朝九晚五工作时间内每半小时
  6. 0 0 12 ? * WED 表示每个星期三中午12
  7. 0 0 12 * * ? 每天中午12点触发
  8. 0 15 10 ? * * 每天上午10:15触发
  9. 0 15 10 * * ? 每天上午10:15触发
  10. 0 15 10 * * ? 每天上午10:15触发
  11. 0 15 10 * * ? 2005 2005年的每天上午10:15触发
  12. 0 * 14 * * ? 在每天下午2点到下午2:59期间的每1分钟触发
  13. 0 0/5 14 * * ? 在每天下午2点到下午2:55期间的每5分钟触发
  14. 0 0/5 14,18 * * ? 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
  15. 0 0-5 14 * * ? 在每天下午2点到下午2:05期间的每1分钟触发
  16. 0 10,44 14 ? 3 WED 每年三月的星期三的下午2:102:44触发
  17. 0 15 10 ? * MON-FRI 周一至周五的上午10:15触发
  18. 0 15 10 15 * ? 每月15日上午10:15触发
  19. 0 15 10 L * ? 每月最后一日的上午10:15触发
  20. 0 15 10 ? * 6L 每月的最后一个星期五上午10:15触发
  21. 0 15 10 ? * 6L 2002-2005 2002年至2005年的每月的最后一个星期五上午10:15触发
  22. 0 15 10 ? * 6#3 每月的第三个星期五上午10:15触发

 

更多cron表达式请参阅:

https://www.jianshu.com/p/b4b8950fb987    《简书--cron表达式》

https://www.matools.com/cron  《crom在线表达式生成器》

 

本博客写作参考文档相关:

https://www.jianshu.com/p/a7097a21b42d

https://blog.csdn.net/SixthMagnitude/article/details/114173570

https://www.bilibili.com/video/BV1PE411i7CV?p=52

https://www.jianshu.com/p/b4b8950fb987    《简书--cron表达式》

https://www.matools.com/cron  《crom在线表达式生成器》

 

示例代码已上传至Github地址:

https://github.com/devyf/SpringBoot_Study/tree/master/helloword_create

原文链接:http://www.cnblogs.com/yif0118/p/14560486.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号