異步任務(wù)
在Java應(yīng)用中,絕大多數(shù)情況下都是通過同步的方式來實現(xiàn)交互處理的;但是在處理與第三方系統(tǒng)交互的時候,容易造成響應(yīng)遲緩的情況,之前大部分都是使用多線程來完成此類任務(wù),其實,在Spring 3.x之后,就已經(jīng)內(nèi)置了@Async來完美解決這個問題。
SpringBoot 實現(xiàn)比較簡單
主啟動類:添加 注釋:@EnableAsync
@EnableScheduling
@EnableAsync
@MapperScan("com.hrp.**.dao")
@SpringBootApplication
public class EcsApplication {
public static void main(String[] args) {
SpringApplication.run(EcsApplication.class, args);
}
}
業(yè)務(wù)方法添加 @Async
@Async
@Override
public void TestAsync() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("-------------");
}
controller調(diào)用
@RequestMapping("myFreeMark")
public String myFreeMark(Map<String,Object> map){
map.put("name","zhangsan");
map.put("mydate",new Date());
asyncServer.TestAsync();
System.out.println("==================FreemarkerController=======myFreeMark=====");
return "myFreeMark";
}
訪問看到控制臺打印順序可以知道TestAsync方法異步調(diào)用
定時任務(wù)
項目開發(fā)中經(jīng)常需要執(zhí)行一些定時任務(wù),比如需要在每天凌晨時候,分析一次前
一天的日志信息。Spring為我們提供了異步執(zhí)行任務(wù)調(diào)度的方式,提供TaskExecutor 、TaskScheduler 接口。
主啟動類:增加@EnableScheduling
@EnableScheduling
@EnableAsync
@MapperScan("com.hrp.**.dao")
@SpringBootApplication
public class EcsApplication {
public static void main(String[] args) {
SpringApplication.run(EcsApplication.class, args);
}
}
任務(wù)類:類增加@Service或者@Compont注釋方法增加@Scheduled注解
@Service
public class BackUpMysqlTask {
/**
* Seconds : 可出現(xiàn)", - * /"四個字符,有效范圍為0-59的整數(shù)
* Minutes : 可出現(xiàn)", - * /"四個字符,有效范圍為0-59的整數(shù)
* Hours : 可出現(xiàn)", - * /"四個字符,有效范圍為0-23的整數(shù)
* DayofMonth : 可出現(xiàn)", - * / ? L W C"八個字符,有效范圍為0-31的整數(shù)
* Month : 可出現(xiàn)", - * /"四個字符,有效范圍為1-12的整數(shù)或JAN-DEc
* DayofWeek : 可出現(xiàn)", - * / ? L C #"四個字符,有效范圍為1-7的整數(shù)或SUN-SAT兩個范圍。1表示星期天,2表示星期一, 依次類推
* Year : 可出現(xiàn)", - * /"四個字符,有效范圍為1970-2099年
*/
@Scheduled(cron = "0 * * * * MON-FRI")
public void backUpMysql() {
System.out.println("===============");
}
}
我們可以觀察到控制臺不斷的再打印
這里要講解cron
/**
* Seconds : 可出現(xiàn)", - * /"四個字符,有效范圍為0-59的整數(shù)
* Minutes : 可出現(xiàn)", - * /"四個字符,有效范圍為0-59的整數(shù)
* Hours : 可出現(xiàn)", - * /"四個字符,有效范圍為0-23的整數(shù)
* DayofMonth : 可出現(xiàn)", - * / ? L W C"八個字符,有效范圍為0-31的整數(shù)
* Month : 可出現(xiàn)", - * /"四個字符,有效范圍為1-12的整數(shù)或JAN-DEc
* DayofWeek : 可出現(xiàn)", - * / ? L C #"四個字符,有效范圍為1-7的整數(shù)或SUN-SAT兩個范圍。1表示星期天,2表示星期一, 依次類推
* Year : 可出現(xiàn)", - * /"四個字符,有效范圍為1970-2099年
*/
下面簡單舉幾個例子:
“0 0 12 * * ?” 每天中午十二點觸發(fā)
“0 15 10 ? * *” 每天早上10:15觸發(fā)
“0 15 10 * * ?” 每天早上10:15觸發(fā)
“0 15 10 * * ? *” 每天早上10:15觸發(fā)
“0 15 10 * * ? 2005” 2005年的每天早上10:15觸發(fā)
“0 * 14 * * ?” 每天從下午2點開始到2點59分每分鐘一次觸發(fā)
“0 0/5 14 * * ?” 每天從下午2點開始到2:55分結(jié)束每5分鐘一次觸發(fā)
“0 0/5 14,18 * * ?” 每天的下午2點至2:55和6點至6點55分兩個時間段內(nèi)每5分鐘一次觸發(fā)
“0 0-5 14 * * ?” 每天14:00至14:05每分鐘一次觸發(fā)
“0 10,44 14 ? 3 WED” 三月的每周三的14:10和14:44觸發(fā)
“0 15 10 ? * MON-FRI” 每個周一、周二、周三、周四、周五的10:15觸發(fā)
郵件任務(wù)
準(zhǔn)備工作
做過郵件的都大家都知道
所以我們要是使用qq郵箱發(fā)送必須有登錄qq郵箱的權(quán)限
開啟smtp服務(wù),發(fā)送短信我們就可以獲取一個授權(quán)碼,自己拷貝下來下圖的授權(quán)碼記錄下來
開始
添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
配置
mail:
host: smtp.qq.com 其他郵箱需要修改
username: 郵箱賬戶
password: 授權(quán)碼
properties:
mail:
smtp:
ssl:
enable: true
測試代碼
@Autowired
private JavaMailSender javaMailSender;
@Test
void contextLoads() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setText("ddd");
simpleMailMessage.setSubject("主題");
simpleMailMessage.setTo("");
simpleMailMessage.setFrom("");
javaMailSender.send(simpleMailMessage);
}
我們可以查收到郵件
上面是普通的郵件
發(fā)送html內(nèi)容
@Test
public void testSend() throws MessagingException {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
messageHelper.setSubject("標(biāo)題");
messageHelper.setTo("@dhcc.com.cn");
messageHelper.setFrom("@qq.com");
messageHelper.setText("<h1>標(biāo)題</h1><br/><p>這是內(nèi)容</p>", true);
javaMailSender.send(messageHelper.getMimeMessage());
}
這里需要注意的是,setText的時候需要傳一個布爾值進(jìn)去,表名需要使用HTML樣式。文章來源:http://www.zghlxwxcb.cn/news/detail-692154.html
最后代碼附件文章來源地址http://www.zghlxwxcb.cn/news/detail-692154.html
package com.hrp.msage.service;
import javax.mail.MessagingException;
/**
* ecs
*
* @Title: com.hrp.msage.service
* @Date: 2020/7/29 13:48
* @Author: wfg
* @Description:
* @Version:
*/
public interface MailService {
/**
* 簡單文本郵件
* @param to 接收者郵件
* @param subject 郵件主題
* @param contnet 郵件內(nèi)容
*/
public void sendSimpleMail(String to, String subject, String contnet);
/**
* HTML 文本郵件
* @param to 接收者郵件
* @param subject 郵件主題
* @param contnet HTML內(nèi)容
* @throws MessagingException
*/
public void sendHtmlMail(String to, String subject, String contnet) throws MessagingException;
/**
* 附件郵件
* @param to 接收者郵件
* @param subject 郵件主題
* @param contnet HTML內(nèi)容
* @param filePath 附件路徑
* @throws MessagingException
*/
public void sendAttachmentsMail(String to, String subject, String contnet,
String filePath) throws MessagingException;
/**
* 圖片郵件
* @param to 接收者郵件
* @param subject 郵件主題
* @param contnet HTML內(nèi)容
* @param rscPath 圖片路徑
* @param rscId 圖片ID
* @throws MessagingException
*/
public void sendInlinkResourceMail(String to, String subject, String contnet,
String rscPath, String rscId);
}
package com.hrp.msage.serviceImpl;
import com.hrp.msage.service.MailService;
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;
/**
* ecs
*
* @Title: com.hrp.msage.serviceImpl
* @Date: 2020/7/29 13:48
* @Author: wfg
* @Description:
* @Version:
*/
@Service("mailService")
public class MailServiceImpl implements MailService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${spring.mail.username}")
private String from;
@Autowired
private JavaMailSender mailSender;
/**
* 簡單文本郵件
* @param to 接收者郵件
* @param subject 郵件主題
* @param contnet 郵件內(nèi)容
*/
@Override
public void sendSimpleMail(String to, String subject, String contnet){
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(contnet);
message.setFrom(from);
mailSender.send(message);
}
/**
* HTML 文本郵件
* @param to 接收者郵件
* @param subject 郵件主題
* @param contnet HTML內(nèi)容
* @throws MessagingException
*/
@Override
public void sendHtmlMail(String to, String subject, String contnet) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(contnet, true);
helper.setFrom(from);
mailSender.send(message);
}
/**
* 附件郵件
* @param to 接收者郵件
* @param subject 郵件主題
* @param contnet HTML內(nèi)容
* @param filePath 附件路徑
* @throws MessagingException
*/
@Override
public void sendAttachmentsMail(String to, String subject, String contnet,
String filePath) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(contnet, true);
helper.setFrom(from);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = file.getFilename();
helper.addAttachment(fileName, file);
mailSender.send(message);
}
/**
* 圖片郵件
* @param to 接收者郵件
* @param subject 郵件主題
* @param contnet HTML內(nèi)容
* @param rscPath 圖片路徑
* @param rscId 圖片ID
* @throws MessagingException
*/
@Override
public void sendInlinkResourceMail(String to, String subject, String contnet,
String rscPath, String rscId) {
logger.info("發(fā)送靜態(tài)郵件開始: {},{},{},{},{}", to, subject, contnet, rscPath, rscId);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = null;
try {
helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(contnet, true);
helper.setFrom(from);
FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);
mailSender.send(message);
logger.info("發(fā)送靜態(tài)郵件成功!");
} catch (MessagingException e) {
logger.info("發(fā)送靜態(tài)郵件失敗: ", e);
}
}
}
package com.hrp;
import com.hrp.msage.service.MailService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.mail.MessagingException;
/**
* ecs
*
* @Title: com.hrp
* @Date: 2020/7/29 13:57
* @Author: wfg
* @Description:
* @Version:
*/
@SpringBootTest
public class MailServiceTest {
@Autowired
private MailService mailService;
// @Resource
// private TemplateEngine templateEngine;
@Test
public void sendSimpleMail() {
mailService.sendSimpleMail("wufagang@dhcc.com.cn","測試spring boot imail-主題","測試spring boot imail - 內(nèi)容");
}
@Test
public void sendHtmlMail() throws MessagingException {
String content = "<html>\n" +
"<body>\n" +
"<h3>hello world</h3>\n" +
"<h1>html</h1>\n" +
"<body>\n" +
"</html>\n";
mailService.sendHtmlMail("wufagang@dhcc.com.cn","這是一封HTML郵件",content);
}
@Test
public void sendAttachmentsMail() throws MessagingException {
String filePath = "D:\\projects\\20200727\\ecs\\src\\main\\resources\\system.properties";
String content = "<html>\n" +
"<body>\n" +
"<h3>hello world</h3>\n" +
"<h1>html</h1>\n" +
"<h1>附件傳輸</h1>\n" +
"<body>\n" +
"</html>\n";
mailService.sendAttachmentsMail("wufagang@dhcc.com.cn","這是一封HTML郵件",content, filePath);
}
@Test
public void sendInlinkResourceMail() throws MessagingException {
//TODO 改為本地圖片目錄
String imgPath = "D:\\projects\\20200727\\ecs\\src\\main\\resources\\imag\\IMG_20200625_104833.jpg";
String rscId = "admxj001";
String content = "<html>" +
"<body>" +
"<h3>hello world</h3>" +
"<h1>html</h1>" +
"<h1>圖片郵件</h1>" +
"<img src='cid:"+rscId+"'></img>" +
"<body>" +
"</html>";
mailService.sendInlinkResourceMail("wufagang@dhcc.com.cn","這是一封圖片郵件",content, imgPath, rscId);
}
@Test
public void testTemplateMailTest() throws MessagingException {
// Context context = new Context();
// context.setVariable("id","ispringboot");
//
// String emailContent = templateEngine.process("emailTeplate", context);
// mailService.sendHtmlMail("ispringboot@163.com","這是一封HTML模板郵件",emailContent);
}
}
到了這里,關(guān)于springboot 與異步任務(wù),定時任務(wù),郵件任務(wù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!