[java framework] SpringBoot--SpringBoot implements asynchronous, email and scheduled tasks

1.SpringBoot integration task mechanism

1.1. Spring boot implements asynchronous methods

Daily development involves many interactive responses between the interface and the back-end, which are not synchronous. Spring boot provides us with an annotation method to implement asynchronous methods. Make the request response of the front end and the business logic method of the back end execute asynchronously. Improved customer experience. I can't help but say that the encapsulation of SpringBoot is indeed exquisite and powerful. In the past, multithreading and Ajax were needed to realize asynchrony. After the underlying encapsulation of SpringBoot, the two annotations are Over!

① You need to enable asynchrony on the SpringApplication execution class. Use @ EnableAsync:

@SpringBootApplication
@EnableAsync  //Turn on asynchronous
public class SpringtestApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringtestApplication.class, args);
    }

}

② At the same time, @ Async is added to the method that takes time to execute the call, indicating that the method is asynchronous:

Copy code
@Service
public class AsyncService {
    @Async
    public void execute(){
        try {
            Thread.sleep(3000);  //Perform system time-consuming tasks
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Task execution succeeded!");
    }
}
Copy code

③ When the asynchronous method called by the Controller layer is executed, the method will be executed asynchronously, the response "success" will be returned, and the background time-consuming method will be executed asynchronously at the same time:

Copy code
@RestController
public class AsyncController {
    @Autowired
    private AsyncService service;

    @RequestMapping("/execute")
    public String executeTask(){
        service.execute();  //Asynchronous execution 3s
        return "success";   //Asynchronous return result
    }
}
Copy code

1.2.SpringBoot implements mail sending

The specific steps for sending mail in Spring Boot are as follows

1. Add Starter module dependency

2. Add Spring Boot configuration (QQ / Netease / Gmail)

3. Call JavaMailSender interface to send mail

① In POM Add mail sending starter dependency in XML:

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

② Send it to the corresponding QQ mailbox, go to the QQ mailbox client, start the POP3/SMTP service, and obtain the authorization code:

③ Add configuration parameters in application Configure email sending method in YML:

QQ email:

# QQ mailbox configuration
spring:
  mail:
    host: smtp.qq.com #outgoing mail server
    username: 241667****@qq.com #Email address for sending mail
    password: ************ #The client authorization code is not the mailbox password, which is automatically generated in the qq mailbox settings
    properties.mail.smtp.port: 465 #Port number 465 or 587
    from: 241667****@qq.com # The email address is the same as the username above
    protocol: smtps  #If the port used is 465, change the smtp of the protocol to smtp s; If the profile port is 587, you can use smtp.
  #Turn on encryption verification
  properties.mail.smtp.ssl.enable: true
 Copy code

Netease email:

##Netease (126 / 163 / year) mailbox configuration
spring:
  mail:
    host: smtp.163.com #outgoing mail server
    username: hyfmail****@163.com #Email address for sending mail
    password: ************ #The client authorization code is not the mailbox password, but Netease's is set by itself
    properties.mail.smtp.port: 465 #465 or 994
    from: hyfmail****@163.com # The email address is the same as the username above
    properties.mail.smtp.ssl.enable: true
    default-encoding: utf-8

④ Write the mail sending interface and implement the following classes:

public interface IMailService {
    /**
     * Send message text
     * @param to addressee
     * @param subject theme
     * @param content content
     */
    void sendSimpleMail(String to, String subject, String content);

    /**
     * Send HTML mail
     * @param to addressee
     * @param subject theme
     * @param content content
     */
    public void sendHtmlMail(String to, String subject, String content);

    /**
     * Send mail with attachments
     * @param to addressee
     * @param subject theme
     * @param content content
     * @param filePath enclosure
     */
    public void sendAttachmentsMail(String to, String subject, String content, String filePath);
}
Copy code
@Service
public class MailServiceImpl implements IMailService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * Spring Boot It provides a simple abstraction for sending e-mail. It uses the following interface, which can be directly injected here
     */
    @Autowired
    private JavaMailSenderImpl mailSender;

    /**
     * My qq mailbox in profile
     */
    @Value("${spring.mail.from}")
    private String from;

    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        //Create a SimpleMailMessage object
        SimpleMailMessage message = new SimpleMailMessage();
        //Mail sender
        message.setFrom(from);
        //Mail recipient
        message.setTo(to);
        //Mail subject
        message.setSubject(subject);
        //Mail content
        message.setText(content);
        //Send mail
        mailSender.send(message);
    }

    /**
     * html mail
     * @param to addressee
     * @param subject theme
     * @param content content
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        //Get MimeMessage object
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            messageHelper = new MimeMessageHelper(message, true);
            //Mail sender
            messageHelper.setFrom(from);
            //Mail recipient
            messageHelper.setTo(to);
            //Mail subject
            message.setSubject(subject);
            //Mail content, html format
            messageHelper.setText(content, true);
            //send out
            mailSender.send(message);
            //log information
            logger.info("The message has been sent.");
        } catch (MessagingException e) {
            logger.error("An exception occurred while sending mail!", e);
        }
    }

    /**
     * Mail with attachments
     * @param to addressee
     * @param subject theme
     * @param content content
     * @param filePath enclosure
     */
    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
            mailSender.send(message);
            //log information
            logger.info("The message has been sent.");
        } catch (MessagingException e) {
            logger.error("An exception occurred while sending mail!", e);
        }
    }
}
Copy code

⑤ Write test class:

Copy code
@SpringBootTest(classes = {SendmailApplication.class})
@RunWith(SpringRunner.class)
public class MailAppTest {

    @Autowired
    private IMailService mailService;

    /**
     * Test sending text mail
     */
    @Test
    public void testSendMail() {
        mailService.sendSimpleMail("hyfmailsave@163.com","Subject: Hello, ordinary mail","Content: first email");
    }

    /**
     * Test sending Html mail
     */
    @Test
    public void sendHtmlMail(){
        mailService.sendHtmlMail("hyfmailsave@163.com","Subject: Hello html mail","<h1>Content: first letter html mail</h1>");
    }

    @Test
    public void sendMimeContentMail(){
        mailService.sendAttachmentsMail("hyfmailsave@163.com", "Subject: Hello, complex email with attachments",
                "<p style='color:red'>Thank you for your html Email and greetings~</p>", "E:\\Workspaces\\SpringBoot_Study\\springboot_test\\src\\main\\resources\\static\\1.jpg");
    }
}
Copy code

 

1.3. Scheduled task

Two important interfaces and two task scheduling annotations are mainly used to execute scheduled tasks in SpringBoot:

  • TaskScheduler task scheduler
  • TaskExecutor
  • @Enableshcheduling: Annotation for enabling the timing function
  • @Scheduled is used for methods that need to be executed regularly. It means to execute regularly at a certain time

The corresponding notes are used as follows:

Startup class:

Copy code
@SpringBootApplication
@EnableAsync  //Turn on asynchronous
@EnableScheduling  //Notes for turning on the timing function
public class SpringtestApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringtestApplication.class, args);
    }

}

Starting method:

@Service
public class ScheduleService {
    //The annotation @ Scheduled is executed regularly. cron expression is required for Scheduled task execution
    //Indicates that it is triggered at 13:43 p.m. every day
    @Scheduled(cron = "0 43 13 ? * *")
    public void timeExecute(){
        System.out.println("The task was triggered to execute~~~");
    }
}

Start the SpringBoot project, and SpringBoot will start the scheduled task execution, scan the annotations that need to be executed regularly in the method, and execute relevant tasks regularly.

Common cron expressions are as follows:

0 0 2 1 * ? Indicates that the task is adjusted at 2 a.m. on the first day of each month

0 15 10 ? * MON-FRI It means 10 a.m. every day from Monday to Friday:15 Execute job

0 15 10 ? 6L 2002-2006 Indicates 2002-2006 10 a.m. on the last Friday of each month in:15 Executive work

0 0 10,14,16 * * ? Every day at 10 a.m., 2 p.m. and 4 p.m

0 0/30 9-17 * * ? Every half an hour during nine to five working hours

0 0 12 ? * WED It means 12 noon every Wednesday

0 0 12 * * ? Triggered at 12 noon every day

0 15 10 ? * * 10 a.m. every day:15 trigger

0 15 10 * * ? 10 a.m. every day:15 trigger

0 15 10 * * ? 10 a.m. every day:15 trigger

0 15 10 * * ? 2005 2005 10 a.m. every day in:15 trigger

0 * 14 * * ? Every day from 2 p.m. to 2 p.m:59 Triggered every 1 minute during

0 0/5 14 * * ? Every day from 2 p.m. to 2 p.m:55 Triggered every 5 minutes during

0 0/5 14,18 * * ? Every day from 2 p.m. to 2 p.m:55 During and from 6 p.m. to 6 p.m:55 Triggered every 5 minutes during

0 0-5 14 * * ? Every day from 2 p.m. to 2 p.m:05 Triggered every 1 minute during

0 10,44 14 ? 3 WED Every Wednesday in March at 2 p.m:10 And 2:44 trigger

0 15 10 ? * MON-FRI Monday to Friday at 10 a.m:15 trigger

0 15 10 15 * ? 10 a.m. on the 15th of each month:15 trigger

0 15 10 L * ? 10 a.m. on the last day of each month:15 trigger

0 15 10 ? * 6L 10 a.m. on the last Friday of each month:15 trigger

0 15 10 ? * 6L 2002-2005 2002 10 a.m. on the last Friday of each month from 2005 to 2005:15 trigger

0 15 10 ? * 6#3 triggered at 10:15 a.m. on the third Friday of each month
 Copy code

 

Keywords: Java Spring Spring Boot

Added by duvys on Sat, 05 Mar 2022 16:09:27 +0200