SpringBoot --- task management (including asynchronous, timing and mail sending)

preparation in advance

1. Create a spring web project in POM Adding dependencies to XML

 <!--     Front end template-->       
<dependency>
  <groupId>org.springframework.boot</groupId>   <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!--     task scheduling --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> <!--     Mail service dependent initiator --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <!--     Generate random number--> <dependency> <groupId>net.bytebuddy</groupId> <artifactId>byte-buddy</artifactId> </dependency>

2. Project structure

3. Add annotation to startup class

 

Asynchronous task scheduling

1. Write asynchronous task scheduling methods, including methods with return value and methods without return value (note that you must remember to write Service in front of the class). It is originally to implement the class. For simplicity, it is written directly here.

@Service
public class MyAsyncServiceImpl{

    @Async
    public void sendSMS() throws Exception{
        System.out.println("Call SMS verification code service method...");
        Long startTime=System.currentTimeMillis();
        Thread.sleep(5000);
        Long endTime=System.currentTimeMillis();
        System.out.println("Completion of SMS service, time consuming:"+(endTime-startTime));}

    @Async
   public Future<Integer> processA() throws Exception { System.out.println("Start analyzing statistical business A Data..."); Long startTime=System.currentTimeMillis(); Thread.sleep(4000); int count=12345; Long endTime=System.currentTimeMillis(); System.out.println("business A Data statistics time:"+(endTime-startTime)); return new AsyncResult<>(count);} @Async public Future<Integer> processB() throws Exception { System.out.println("Start analyzing statistical business B Data..."); Long startTime=System.currentTimeMillis(); Thread.sleep(5000); int count=165432; Long endTime=System.currentTimeMillis(); System.out.println("business B Data statistics time:"+(endTime-startTime)); return new AsyncResult<>(count);} }

2. Write MyAsncController control class

@RestController
public class MyAsyncController {
    @Autowired
    MyAsyncService myAsyncService;

    @GetMapping("/sendSms")
    public String sendSMS()throws Exception{
        Long startTime=System.currentTimeMillis(); //start time
        myAsyncService.sendSMS();
        Long endTime=System.currentTimeMillis(); //End time
        System.out.println("Main flow time:"+(endTime-startTime));
        return "success"; }

    @GetMapping("/statistics")
    public String statistics() throws Exception{
        Long startTime=System.currentTimeMillis();  //start time
        Future<Integer> futureA=myAsyncService.processA();
        Future<Integer> futureB=myAsyncService.processB();
        int total=futureA.get()+futureB.get();
        System.out.println("Summary results of asynchronous task data statistics:"+total);
        Long endTime=System.currentTimeMillis();  //End time
        System.out.println("Main flow time:"+(endTime-startTime));
        return "success";}
}

3. Operation results

Analysis results:

1. The called SMS service has no callback, and the main process does not need to wait for the completion of the SMS service, so the main process time (15 seconds) has nothing to do with the time of the SMS service.

2. The data statistics method has callback. The main process needs to wait for the return value before it can be executed. In addition, the time-consuming of business A and business B is 4 seconds and 5 seconds. Because they are executed asynchronously (sleep), the total time-consuming is about 5 seconds

 

Scheduled task scheduling

Test fixedRate, Fixed delay, cron and other three ways of scheduled task scheduling

1. Write the service class and add the service method of fixedRate

@Service
public class ScheduledTaskServiceImpl {
    static final DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
    int count1=1;
    int count2=1;
    int count3=1;

    @Scheduled(fixedRate = 5000) //Execute every 5 seconds, including execution time
    public void scheduledFixRate() {
        System.out.println(String.format("fixeRate The first %s The current time is %s",count1++,dtf.format(LocalDateTime.now())));}
}

Start the project and view the console output

2. Add the service method of fixedDelay and annotate the method of fixedRate

 @Scheduled(fixedDelay = 6000)  //Execute every 6 seconds, excluding execution time
    public void scheduleTaskImmediately() throws Exception{
        System.out.println(String.format("fixeDelay The first %s The current time is %s",count2++,dtf.format(LocalDateTime.now())));
        Thread.sleep(4000);
    }

Start the project and view the console output

3. Add cron based task scheduling methods, and annotate the fixedRate and fixedDelay methods

@Scheduled(cron="0 * * * * *") //Timed execution every minute
    public void scheduledTaskCorn(){
        System.out.println(
                String.format("cron The first%s The current time is %s",count3++,dtf.format(LocalDateTime.now())) );
    }

Start the project and view the console output

 

Mail task

1. Register a 163 or QQ or other email account, open the smtp service of the client, and obtain the registration code at the same time.

 

2. Write application configuration file

#Mailbox server
spring.mail.host=smtp.163.com
#Login email account (replace with your email account)
spring.mail.username=*****@163.com
#Here is the password authorized by your client just now, not the password of your login email (replace it with your authorization code)
spring.mail.password=**************
#agreement
spring.mail.protocol=smtps
#Mailbox server port
spring.mail.port=465
#Coding settings
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
#Set timeout
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=3000
spring.mail.properties.mail.smtp.writetimeout=5000

3. Write the mail sending service class SendEmailService

@Service
public class SendEmailServiceImpl{
    @Autowired
    JavaMailSenderImpl javaMailSender;
@Value(
"${spring.mail.username}") private String sender; @Async public void sendEmail(String receiver, String subject, String content) { SimpleMailMessage message=new SimpleMailMessage(); message.setFrom(sender); message.setTo(receiver); message.setSubject(subject); message.setText(content); try{ javaMailSender.send(message); }catch (MailException e){ System.out.println("Mail sending failed"); e.printStackTrace(); } } }

4. Write controller EmailController

@RestController
public class EmailController {
    @Autowired
    SendEmailService sendEmailService;

    @Autowired
    TemplateEngine templateEngine;

   @GetMapping("/sendSimpleEmail")
    public String sendSimpleEmail(){
       String receiver="****@qq.com"; 
       String subject="springboot Mail sending test";
       String content="A letter from SpringBoot 163 messages sent, asynchronous sending mode";
       sendEmailService.sendEmail(receiver,subject,content);
       return "Mail sent successfully, please check email";}
}

5. Open the browser, access the controller address for testing, record the test results, and observe the console output. Check the target mailbox to see if you have received mail.

 

 

Email sending of template

1. Add the following code in SendEmailService

   @Async
    public void sendTemplateEmail(String receiver,String subject,String content){
        MimeMessage message=javaMailSender.createMimeMessage();
        try{
            MimeMessageHelper helper=new MimeMessageHelper(message,true);
            helper.setFrom(sender);
            helper.setTo(receiver);
            helper.setSubject(subject);
            helper.setText(content,true);
            javaMailSender.send(message);
            System.out.println("Mail sent successfully");
        }catch (Exception e){
            System.out.println("Mail sending failed");
            e.printStackTrace();
        }
    }

2,emailTemplate.html file

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>User check code</title>
</head>
<body>
<div><span th:text="${username}">***</span> ma'am/Hello, sir
</div>
<p style="text-indent: 2em">Your user verification code is:<span th:text="${code}" style="color: aqua;">
</span>Please keep it properly and don't disclose it to others. </p>
</body>
</html>

3. Add the following method in EmailController

@GetMapping("/sendEmail")
    public String sendEmailByTemplate(){
       String receiver="*****@qq.com";
       String subject="Sending template mail";
       //Customize message body content using template mail
        Context context=new Context();
        String code= RandomString.make(5);

        context.setVariable("username","***");
        context.setVariable("code",code);
        //use TemplateEngine Set template pages to process
        String emailContent=templateEngine.process("emailTemplate",context);
        //Send template mail
        sendEmailService.sendTemplateEmail(receiver,subject,emailContent);
        return "The email was sent successfully. The check code is:"+code;
    }

4. Open the browser, access the controller address for testing, record the test results, and observe the console output. Check the target mailbox to see if you have received mail.

<dependency>

Tags: JavaEE Spring Boot

Posted by jraede on Tue, 17 May 2022 20:28:27 +0300