前言
springBoot之任务的初探,包含了异步任务、定时任务和邮件任务三大点,如果出现相关问题欢迎批评指正
以下是本篇文章正文内容
任务
1.异步任务
- 使用方法:
①在方法头写@Async注解
②在application方法上开启@enableAsync注解 - 代码片段:
package com.warrior.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
@Async//异步方法
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理");
}
}
//******************************************************************
@SpringBootApplication
@EnableAsync//开启异步注解的方法
public class SpringDataApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDataApplication.class, args);
}
}
开启异步任务后相当于开启多线程,一边处理后台的数据,一边不耽误前端页面的显示
2.定时任务
Cron表达式是一个字符串,字符串以5或6个空格隔开,分为6或7个域,每一个域代表一个含义,Cron有如下两种语法格式:
(1) Seconds Minutes Hours DayofMonth Month DayofWeek Year
(2)Seconds Minutes Hours DayofMonth Month DayofWeek
结构:corn从左到右(用空格隔开):秒 分 小时 月份中的日期 月份 星期中的日期 年份
- 两个用到的接口
TaskScheduler //任务调度者
TaskExecutor //任务执行者
- 使用步骤
//用到的注解
@EnableScheduling//开启定时功能的注解
@scheduled//什么时候执行
//*********************************
@Service
public class ScheduledService {
//cron表达式
/*
30 15 10 * * ? 每天的10点15分30执行一次
20 0/5 10,18 * * ? 每天10点和18点,每隔5分钟执行一次
0 15 10 ? * 1-6 每个月的周一到周六10点15分执行一次
*/
@Scheduled(cron = "38 39 17 * * ?")//每天的17时39分38秒执行一次
public void hello(){
System.out.println("hello方法被执行");
}
}
//*************************************
package com.warrior;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableAsync//开启异步注解的方法
@EnableScheduling//开启定时功能的注解
public class SpringDataApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDataApplication.class, args);
}
}
3.邮件任务
SMTP是一种提供可靠且有效的电子邮件传输的协议。SMTP是建立在FTP文件传输服务上的一种邮件服务,主要用于系统之间的邮件信息传递,并提供有关来信的通知。SMTP独立于特定的传输子系统,且只需要可靠有序的数据流信道支持,SMTP的重要特性之一是其能跨越网络传输邮件,即“SMTP邮件中继”。使用SMTP,可实现相同网络处理进程之间的邮件传输,也可通过中继器或网关实现某处理进程与其他网络之间的邮件传输。--------百度百科
- 导入mail的jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
- yaml的配置文件写法
spring:
mail:
username: 1129184815@qq.com
password: mqzhijrpthssgheg# 在邮箱里获得的密钥
host: smtp.qq.com
properties: # 键值对的写法
mail:
smtp:
ssl:
enable: true
# 开启加密认证
做一个测试
@Autowired
JavaMailSenderImpl javaMailSender;
@Test
void contextLoads() throws SQLException {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("hello");//邮件主题
mailMessage.setText("这是一封测试邮件");
mailMessage.setTo("********@163.com");//邮件地址
mailMessage.setFrom("*********@qq.com");//发件地址
javaMailSender.send(mailMessage);
}
我们看到这里用到了mailMessage这个对象里的方法,所以我们点开源码看一下这个对象里有哪些方法:
public SimpleMailMessage() {
}
public SimpleMailMessage(SimpleMailMessage original) {
Assert.notNull(original, "'original' message argument must not be null");
this.from = original.getFrom();
this.replyTo = original.getReplyTo();
this.to = copyOrNull(original.getTo());
this.cc = copyOrNull(original.getCc());
this.bcc = copyOrNull(original.getBcc());
this.sentDate = original.getSentDate();
this.subject = original.getSubject();
this.text = original.getText();
}
public void setFrom(String from) {//发件地址
this.from = from;
}
@Nullable
public String getFrom() {
return this.from;
}
public void setReplyTo(String replyTo) {//邮件的回复地址
this.replyTo = replyTo;
}
@Nullable
public String getReplyTo() {
return this.replyTo;
}
public void setTo(String to) {//邮件的发送地址
this.to = new String[]{to};
}
public void setTo(String... to) {
this.to = to;
}
@Nullable
public String[] getTo() {
return this.to;
}
public void setCc(String cc) {
this.cc = new String[]{cc};
}
public void setCc(String... cc) {
this.cc = cc;
}
@Nullable
public String[] getCc() {
return this.cc;
}
public void setBcc(String bcc) {
this.bcc = new String[]{bcc};
}
public void setBcc(String... bcc) {
this.bcc = bcc;
}
@Nullable
public String[] getBcc() {
return this.bcc;
}
public void setSentDate(Date sentDate) {//发送日期
this.sentDate = sentDate;
}
@Nullable
public Date getSentDate() {
return this.sentDate;
}
public void setSubject(String subject) {//发送主题
this.subject = subject;
}
@Nullable
public String getSubject() {
return this.subject;
}
public void setText(String text) {//文本内容
this.text = text;
}
@Nullable
public String getText() {
return this.text;
}
public void copyTo(MailMessage target) {
Assert.notNull(target, "'target' MailMessage must not be null");
if (this.getFrom() != null) {
target.setFrom(this.getFrom());
}
if (this.getReplyTo() != null) {
target.setReplyTo(this.getReplyTo());
}
if (this.getTo() != null) {
target.setTo(copy(this.getTo()));
}
if (this.getCc() != null) {
target.setCc(copy(this.getCc()));
}
if (this.getBcc() != null) {
target.setBcc(copy(this.getBcc()));
}
if (this.getSentDate() != null) {
target.setSentDate(this.getSentDate());
}
if (this.getSubject() != null) {
target.setSubject(this.getSubject());
}
if (this.getText() != null) {
target.setText(this.getText());
}
}
public boolean equals(@Nullable Object other) {
if (this == other) {
return true;
} else if (!(other instanceof SimpleMailMessage)) {
return false;
} else {
SimpleMailMessage otherMessage = (SimpleMailMessage)other;
return ObjectUtils.nullSafeEquals(this.from, otherMessage.from) && ObjectUtils.nullSafeEquals(this.replyTo, otherMessage.replyTo) && ObjectUtils.nullSafeEquals(this.to, otherMessage.to) && ObjectUtils.nullSafeEquals(this.cc, otherMessage.cc) && ObjectUtils.nullSafeEquals(this.bcc, otherMessage.bcc) && ObjectUtils.nullSafeEquals(this.sentDate, otherMessage.sentDate) && ObjectUtils.nullSafeEquals(this.subject, otherMessage.subject) && ObjectUtils.nullSafeEquals(this.text, otherMessage.text);
}
}
public int hashCode() {
int hashCode = ObjectUtils.nullSafeHashCode(this.from);
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.replyTo);
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.to);
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.cc);
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.bcc);
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.sentDate);
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.subject);
return hashCode;
}
public String toString() {
StringBuilder sb = new StringBuilder("SimpleMailMessage: ");
sb.append("from=").append(this.from).append("; ");
sb.append("replyTo=").append(this.replyTo).append("; ");
sb.append("to=").append(StringUtils.arrayToCommaDelimitedString(this.to)).append("; ");
sb.append("cc=").append(StringUtils.arrayToCommaDelimitedString(this.cc)).append("; ");
sb.append("bcc=").append(StringUtils.arrayToCommaDelimitedString(this.bcc)).append("; ");
sb.append("sentDate=").append(this.sentDate).append("; ");
sb.append("subject=").append(this.subject).append("; ");
sb.append("text=").append(this.text);
return sb.toString();
}
@Nullable
private static String[] copyOrNull(@Nullable String[] state) {
return state == null ? null : copy(state);
}
private static String[] copy(String[] state) {
return (String[])state.clone();
}
测试结果:
3. 复杂邮件
- 代码部分
@Test
void contextLoads2() throws MessagingException {
//复杂邮件的创建
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//组装
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
helper.setSubject("复杂邮件的测试主题");
helper.setText("<h1>复杂邮件的测试内容<h1/><br/>这句话是一个普通文本",true);
//后边的参数表示可以解释标签语言
//附件
helper.addAttachment("pic.jpg", new File("C:\\Users\\****\\Pictures\\Saved Pictures\\pic.jpg"));
//可以使用本地的绝对路径
//发送
helper.setTo("*********.com");
helper.setFrom("warrior");
javaMailSender.send(mimeMessage);
}
- 结果
在实际开发过程中,需要完成邮件业务的时候,可以将代码封装成一个方法,直接调用就可以。
总结
异步任务主要解决了多线程的等待问题定时任务通过两个注解和cron表达式确定任务的开始时间
邮件任务解决了简单邮件和复杂邮件的发送问题