1.在主类或者配置类上使用@EnableAsync注解开启异步任务
@SpringBootApplication
@MapperScan(basePackages = "com.limi.springboottest2.mapper")
@EnableAsync //开启异步任务
public class SpringbootTest2Application {
;
public static void main(String[] args) {
//1、返回我们IOC容器
ConfigurableApplicationContext run = SpringApplication.run(SpringbootTest2Application.class, args);
}
}
2.编写异步任务
package com.limi.springboottest2.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
@Async
public void say(){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("异步任务处理中...");
}
}
3.测试执行
@Autowired
private AsyncService asyncService;
@ResponseBody
@GetMapping("/test1")
public String test(){
asyncService.say();
return "ok";
}
访问立即得到返回数据


项目开发中经常需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息。Spring为我们提供了异步执行任务调度的方式,提供
TaskExecutor 、TaskScheduler 接口。
两个注解:@EnableScheduling、@Scheduled

1.在配置类或者启动类上使用@EnableScheduling注解开启定时任务
package com.limi.springboottest2;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@MapperScan(basePackages = "com.limi.springboottest2.mapper")
@EnableScheduling //开启定时任务
public class SpringbootTest2Application {
;
public static void main(String[] args) {
//1、返回我们IOC容器
ConfigurableApplicationContext run = SpringApplication.run(SpringbootTest2Application.class, args);
}
}
2.编写定时任务
package com.limi.springboottest2.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class ScheduleService {
@Scheduled(cron = "0/5 * * * * ? ") //每 5s 执行一次
public void test(){
System.out.println("ok");
}
}
cron表达式可使用在线生成器生成, 生成器网址

3.运行测试

• 邮件发送需要引入spring-boot-starter-mail
• Spring Boot 自动配置MailSenderAutoConfiguration
• 定义MailProperties内容,配置在application.yml中 • 自动装配JavaMailSender
• 测试邮件发送
开启QQ邮箱授权码


ryazxwcwiwjubjab
1.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.编写配置
#发送邮件服务器
spring.mail.host=smtp.qq.com
#邮箱账号
spring.mail.username=limimail@qq.com
#邮箱授权码
spring.mail.password=ryaabccwiwjubjab
3.编写代码
邮件服务类MailService
package com.limi.springboottest2.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Service
public class MailService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private JavaMailSender javaMailSender;
//注入配置文件中配置的信息username——>from
@Value("${spring.mail.username}")
private String from;
//简单邮件
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
//发件人
message.setFrom(from);
//收件人
message.setTo(to);
//邮件主题
message.setSubject(subject);
//邮件内容
message.setText(content);
//发送邮件
javaMailSender.send(message);
}
//html邮件
public void sendHtmlMail(String to, String subject, String content) {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper;
try {
messageHelper = new MimeMessageHelper(message,true);
messageHelper.setFrom(from);
messageHelper.setTo(to);
message.setSubject(subject);
messageHelper.setText(content,true);
javaMailSender.send(message);
logger.info("邮件已经发送!");
} catch (MessagingException e) {
logger.error("发送邮件时发生异常:"+e);
}
}
//带附件邮件
public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper;
try {
messageHelper = new MimeMessageHelper(message,true);
messageHelper.setFrom(from);
messageHelper.setTo(to);
messageHelper.setSubject(subject);
messageHelper.setText(content,true);
//携带附件
FileSystemResource file = new FileSystemResource(filePath);
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
messageHelper.addAttachment(fileName,file);
javaMailSender.send(message);
logger.info("邮件加附件发送成功!");
} catch (MessagingException e) {
logger.error("发送失败:"+e);
}
}
}
测试类MyTest
package com.limi.springboottest2;
import com.limi.springboottest2.service.MailService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class MyTest {
@Autowired
private MailService emailService;
@Test
public void sendSimpleEmail(){
String content = "你好,恭喜你...";
emailService.sendSimpleMail("lmail123@163.com","祝福邮件",content);
}
@Test
public void sendMimeEmail(){
String content = "<a href='https://blog.csdn.net/'>你好,欢迎注册网站,请点击链接激活</a>";
emailService.sendHtmlMail("lmail123@163.com","激活邮件",content);
}
@Test
public void sendAttachment(){
emailService.sendAttachmentsMail("lmail123@163.com","发送附件","Spring体系图","E:\\Office文档\\tu\\3.jpg");
}
}
测试结果


