SpringBoot——异步、定时、发送邮件
一、异步任务
在异步执行的函数上使用注解@Async,并在主配置类上启用(@EnableAsync)
@Service
public class AsyncService {
@Async
@Scheduled(cron = "") //定时任务
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("异步:hello!");
}
}
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String hello(){
asyncService.hello();
return "hello world!";
}
}
@EnableAsync //启用异步任务
@EnableScheduling //启用定时任务
@SpringBootApplication
public class Springboot20200603Application {
public static void main(String[] args) {
SpringApplication.run(Springboot20200603Application.class, args);
}
}
二、定时任务
在需要定时执行的函数上添加注解@Scheduled(cron = “”)
cron是定时表达式:
@Scheduled(cron=“0 */5 * * * ?”) //每5分钟执行一次
@Scheduled(cron=“0 */1 * * * ?”) //每1分钟执行一次
三、发送邮件
1.在pom文件中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.配置邮件服务器
spring.mail.username=ning0539@foxmail.com <!--发送邮件的邮箱地址 -->
spring.mail.password=qtfohyuziiszbiic <!--邮箱授权码-->
spring.mail.host=smtp.qq.com <!--通过POP3收取邮件时,发件服务器-->
3.使用JavaMailSenderImpl操作邮件发送
class Springboot20200603ApplicationTests {
@Autowired
JavaMailSenderImpl javaMailSender;
/**
* 发送简单邮件
*/
@Test
void contextLoads() {
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("测试邮箱服务器");//邮件主题
message.setText("测试邮件。");//邮件内容
message.setTo("wang526132456@163.com");//收件人邮箱地址
message.setFrom("ning0539@foxmail.com");//发件人邮箱地址
javaMailSender.send(message);
}
/**
* 发送复杂邮件:附件
*/
@Test
void sendMail() throws Exception {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.setSubject("测试邮箱服务器");
helper.setText("<b style='color:red'>测试复杂邮件。</b>",true);//参数true:是否为html内容
helper.setTo("wang526132456@163.com");
helper.setFrom("ning0539@foxmail.com");
helper.addAttachment("1.jpg",new File("C:\\Users\\K\\Pictures\\1.jpg"));//附件
helper.addAttachment("2.jpg",new File("C:\\Users\\K\\Pictures\\2.jpg"));
javaMailSender.send(mimeMessage);
}
}