SpringBoot中的异步、邮件和定时任务
异步
-
SpringBoot集成了异步功能,只需在主进程类使用注释**@EnableAsync**开启异步功能
-
接着在编写的service类中的当方法为异步执行时使用注释**@Async**即可,SpringBoot通过识别该注释即可知道这个方法为异步方法,会自动生成新的线程去异步执行该方法。
-
@Service public class AsyncService { @Async public void hello() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("数据正在处理。。。。。。"); } }
邮件
-
SpringBoot集成了邮件的功能,首先需要导入maven依赖
-
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
-
接着在application.yml文件中配置邮件的基本信息
-
spring: mail: username: xxx@xx.com password: xxxx host: smtp.qq.com properties: mail.smtp.ssl.enable: true
-
接着编写发送邮件的方法即可,邮件信息对象有两种,一种SimpleMailMessage简单的邮件信息对象,一种MimeMessage用于发送复杂的邮件,邮件发送对象由JavaMailSenderImpl来实现,可通过@Autowired自动注入。
-
@SpringBootTest class DemoJdbcApplicationTests { @Autowired JavaMailSenderImpl mailSender; @Test void contextLoads() throws SQLException { SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); simpleMailMessage.setTo("xxx@xxx.com"); simpleMailMessage.setFrom("xxx@xx.com"); simpleMailMessage.setSubject("你好"); simpleMailMessage.setText("这是一封邮件"); mailSender.send(simpleMailMessage); System.out.println("发送完成"); } @Test void contextLoads1() throws MessagingException { //一个复杂的邮件 MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true); helper.setSubject("这是一封邮件"); helper.setTo("xxx@xxx.com"); helper.setFrom("xxx@xxx.com"); helper.addAttachment("1.jpg",new File("C:\\Users\\Timemachine\\Desktop\\xiaohuangren.jpg")); helper.setText("<p>请接收图片</p>",true); mailSender.send(mimeMessage); } }
定时任务
-
SpringBoot内置集成了定时功能,通过在主进程类中使用注释**@EnableScheduling**开启定时功能
-
接着在需要执行定时任务的方法中使用注释**@Scheduled(cron = “0/2 * 13 * * ?”)**来声明执行的计划时间,计划的时间可以使用cron表达式来声明。可以使用在线cron表达式生成器
-
@Scheduled(cron = "0/2 * 13 * * ?") public void hello(){ System.out.println("hello"); }