springboot and asynchronous tasks, scheduled tasks, email tasks

Asynchronous tasks

In Java applications, in most cases, interactive processing is implemented through synchronization; however, when interacting with third-party systems, it is easy to cause slow response. In the past, most of them were completed using multi-threads. For such tasks, in fact, after Spring 3.x, @Async has been built in to perfectly solve this problem.

SpringBoot implementation is relatively simple.
Main startup class: add annotation: @EnableAsync

@EnableScheduling
@EnableAsync
@MapperScan("com.hrp.**.dao")
@SpringBootApplication
public class EcsApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(EcsApplication.class, args);
    }

}

Add @Async to business methods

 @Async
    @Override
    public void TestAsync() {
    
    
        try {
    
    
            Thread.sleep(5000);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        System.out.println("-------------");
    }

controller call

@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";
    }

Insert image description here
You can know the asynchronous call of TestAsync method by visiting the console printing sequence.

scheduled tasks

In project development, it is often necessary to perform some scheduled tasks. For example, it is necessary to analyze the log information of the previous day in the early morning of every day
. Spring provides us with a way to perform task scheduling asynchronously, providing TaskExecutor and TaskScheduler interfaces.

Main startup class: Add @EnableScheduling

@EnableScheduling
@EnableAsync
@MapperScan("com.hrp.**.dao")
@SpringBootApplication
public class EcsApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(EcsApplication.class, args);
    }

}

Task class: add @Service or @Component annotation method to the class and add @Scheduled annotation

@Service
public class BackUpMysqlTask {
    
    

    /**
     * Seconds : 可出现", - * /"四个字符,有效范围为0-59的整数
     * Minutes : 可出现", - * /"四个字符,有效范围为0-59的整数
     * Hours : 可出现", - * /"四个字符,有效范围为0-23的整数
     * DayofMonth : 可出现", - * / ? L W C"八个字符,有效范围为0-31的整数
     * Month : 可出现", - * /"四个字符,有效范围为1-12的整数或JAN-DEc
     * DayofWeek : 可出现", - * / ? L C #"四个字符,有效范围为1-7的整数或SUN-SAT两个范围。1表示星期天,2表示星期一, 依次类推
     * Year : 可出现", - * /"四个字符,有效范围为1970-2099年
     */
    @Scheduled(cron = "0 * * * * MON-FRI")
    public void backUpMysql() {
    
    
        System.out.println("===============");
    }
}

We can observe that the console is constantly printing again.
Here we will explain cron

Insert image description here
Insert image description here

 /**
     * Seconds : 可出现", - * /"四个字符,有效范围为0-59的整数
     * Minutes : 可出现", - * /"四个字符,有效范围为0-59的整数
     * Hours : 可出现", - * /"四个字符,有效范围为0-23的整数
     * DayofMonth : 可出现", - * / ? L W C"八个字符,有效范围为0-31的整数
     * Month : 可出现", - * /"四个字符,有效范围为1-12的整数或JAN-DEc
     * DayofWeek : 可出现", - * / ? L C #"四个字符,有效范围为1-7的整数或SUN-SAT两个范围。1表示星期天,2表示星期一, 依次类推
     * Year : 可出现", - * /"四个字符,有效范围为1970-2099年
     */

Here are a few simple examples:

"0 0 12 * * ?" triggers
"0 15 10 ? * *" at 12 noon every day. "0 15 10 * * ?" triggers at 10:15 every morning. "0 15 10 * * ? *
triggers at 10:15 every morning.
"Trigger
"0 15 10 * * ? 2005" every morning at 10:15. Trigger "0 * 14 * * ?" every morning 10:15 in 2005. " 0"
every minute from 2 PM to 2:59 every day.
0/5 14 * * ?" Triggers "0 0/5 14,18 * * ?" every 5 minutes from 2 pm to 2:55 pm every day from
2 pm to 2:55 pm and from 6 pm to 6 pm "0 0-5 14 * * ?" is triggered every 5 minutes in the two time periods at 6:55. "0 10,44 14 ? 3 WED"
is triggered every minute from 14:00 to 14:05 every day. Every day in March "0 15 10 ? * MON-FRI"
is triggered at 14:10 and 14:44 on Wednesday. It is triggered at 10:15 every Monday, Tuesday, Wednesday, Thursday and Friday.

Email tasks

Preparation

Everyone who has done email knows
Insert image description here
that if we use qq mailbox to send, we must have permission to log in to qq mailbox
Insert image description here
. Open the smtp service, send a text message and we can get an authorization code. Copy it yourself and record the authorization code in the picture below.
Insert image description here
Insert image description here

start

Add dependencies

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

Configuration

  mail:
    host: smtp.qq.com  其他邮箱需要修改
    username: 邮箱账户
    password: 授权码
    properties:
      mail:
        smtp:
          ssl:
            enable: true

test code

 @Autowired
    private JavaMailSender javaMailSender;
    @Test
    void contextLoads() {
    
    
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setText("ddd");
        simpleMailMessage.setSubject("主题");
        simpleMailMessage.setTo("");
        simpleMailMessage.setFrom("");
        javaMailSender.send(simpleMailMessage);
    }

We can check the mail

The above is an ordinary email

Send html content

 @Test
    public void testSend() throws MessagingException {
    
    
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setSubject("标题");
        messageHelper.setTo("@dhcc.com.cn");
        messageHelper.setFrom("@qq.com");
        messageHelper.setText("<h1>标题</h1><br/><p>这是内容</p>", true);
        javaMailSender.send(messageHelper.getMimeMessage());
    }

What needs to be noted here is that a Boolean value needs to be passed in when settingText, and the table name needs to use HTML style.

Last code attachment

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 邮件内容
     */
    public void sendSimpleMail(String to, String subject, String contnet);
    /**
     * HTML 文本邮件
     * @param to 接收者邮件
     * @param subject 邮件主题
     * @param contnet HTML内容
     * @throws MessagingException
     */
    public void sendHtmlMail(String to, String subject, String contnet) throws MessagingException;
    /**
     * 附件邮件
     * @param to 接收者邮件
     * @param subject 邮件主题
     * @param contnet HTML内容
     * @param filePath 附件路径
     * @throws MessagingException
     */
    public void sendAttachmentsMail(String to, String subject, String contnet,
                                    String filePath) throws MessagingException;
    /**
     * 图片邮件
     * @param to 接收者邮件
     * @param subject 邮件主题
     * @param contnet HTML内容
     * @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 邮件内容
     */
    @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内容
     * @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内容
     * @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内容
     * @param rscPath 图片路径
     * @param rscId 图片ID
     * @throws MessagingException
     */
    @Override
    public void sendInlinkResourceMail(String to, String subject, String contnet,
                                       String rscPath, String rscId) {
    
    
        logger.info("发送静态邮件开始: {},{},{},{},{}", 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("发送静态邮件成功!");

        } catch (MessagingException e) {
    
    
            logger.info("发送静态邮件失败: ", 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("[email protected]","测试spring boot imail-主题","测试spring boot imail - 内容");
    }

    @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("[email protected]","这是一封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("[email protected]","这是一封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("[email protected]","这是一封图片邮件",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("[email protected]","这是一封HTML模板邮件",emailContent);

    }
}

Guess you like

Origin blog.csdn.net/wufagang/article/details/107642887