SpringBoot integration task

1, Spring Boot and tasks

1.1 asynchronous tasks

In Java applications, in most cases, interactive processing is realized through synchronization; However, when dealing with interaction with third-party systems, it is easy to cause slow response. Before, most of them used multithreading to complete such tasks. In fact, in spring 3 After X, the @ Async annotation has been built in to perfectly solve this problem.

There are two notes:

  • @EnableAysnc: mark on the startup class to start the annotation development of asynchronous tasks
  • @Aysnc: mark the tasks to be executed asynchronously

The basic usage is as follows:

  1. Enable asynchronous task annotation support on startup class

    @EnableAsync
    @SpringBootApplication
    public class SpringbootTaskApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringbootTaskApplication.class, args);
        }
    }
    
  2. Mark the @ Async annotation on the method to be executed asynchronously

    @Service
    public class AsyncService {
    
        @Async
        public void hello(){
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Data processing.......");
        }
    }
    
  3. Write Controller

    @RestController
    public class AsyncController {
    
        @Autowired
        AsyncService asyncService;
    
        @RequestMapping("/hello")
        public String hello(){
            asyncService.hello();
            return "success";
        }
    }
    

At this time, accessing the hello method in the Controller will immediately return the result, and the text message will be printed after 3 seconds. At this time, the method call does not have an asynchronous task. If the annotation of the asynchronous task is not enabled, the Controller will return the result after 3 seconds.

1.2 scheduled tasks

During 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 each day. Spring provides us with a way to schedule tasks asynchronously, and provides TaskExecutor and TaskScheduler interfaces.

The main notes are as follows:

  • @Enablesscheduling: mark on the startup class to enable the support of annotation scheduled tasks
  • @Scheduled: above the label and method, define the scheduled execution time of the modified method

The basic usage is as follows:

  1. Enable timed task annotation support on the startup class

    @EnableScheduling
    @SpringBootApplication
    public class SpringbootTaskApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringbootTaskApplication.class, args);
        }
    }
    
  2. Mark @ Scheduled on the task to define when to execute the task

    @Service
    public class ScheduleService {
    
        /**Parameters are separated by spaces
         * second(Second, minute, hour, day of month, month, day of week
         * 0 * * * * MON-FRI
         *  [0 0/5 14,18 * * ?] At 14 o'clock sharp and 18 o'clock sharp every five minutes
         *  [0 15 10 ? * 1-6] It shall be implemented once every month from Monday to Saturday at 10:15
         *  [0 0 2 ? * 6L]At 2 a.m. on the last Saturday of each month
         *  [0 0 2 LW * ?]It is implemented once at 2 a.m. on the last working day of each month
         *  [0 0 2-4 ? * 1#1]From 2:00 a.m. to 4:00 a.m. on the first Monday of each month, it is implemented once every whole hour;
         */
        // @Scheduled(cron = "0 * * * * MON-SAT")
        //@Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT")
        // @Scheduled(cron = "0-4 * * * * MON-SAT")
        @Scheduled(cron = "0 * * * * 0-7")
        public void schedule(){
            System.out.println("schedule.......");
        }
    }
    

cron expression:

fieldOperating valueRun special characters
second0-59,,-,*,/
branch0-59,,-,*,/
Time0-23,,-,*,/
date1-31,,-,*,?,/,L,W,C
month1-12,,-,*,/
week0-7 or SUN-SAT; 0,7 is SUN,,-,*,?,/,L,C,#

Special characters:

Special charactersExpress meaning
,enumeration
-section
*arbitrarily
/step
?Day / week conflict match
Llast
Wweekdays
CCalculated value after contacting calendar
#Thursday, 4#2 the second Thursday

1.3 email tasks

Basic use

  1. Introducing mail dependencies

     	<parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.6.2</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
     	<dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-mail</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
  2. Configure email account and password

    spring:
      mail:
        username: 123@qq.com
    #    Authorization code of qq mailbox
        password: fdsafdsaaasff
    #   Configure qq's host
        host: smtp.qq.com
    
  3. Test mail sending

    @SpringBootTest
    class SpringbootTaskApplicationTests {
    
        @Autowired
        JavaMailSenderImpl mailSender;
    
        @Test
        void contextLoads() {
            //Send simple email
            SimpleMailMessage simpleMail = new SimpleMailMessage();
            //Set the subject of the message
            simpleMail.setSubject("notice-Evening meeting");
            //Set the content of the message
            simpleMail.setText("7 pm:30 attend a meeting");
            //Set the sending account
            simpleMail.setFrom("123@qq.com");
            //Set the received mailbox
            simpleMail.setTo("456@163.com");
            mailSender.send(simpleMail);
        }
    
        @Test
        void contextLoads1() throws MessagingException {
            //Send complex mail
            MimeMessage mimeMessage = mailSender.createMimeMessage();
    
            //Settings can be attached
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
            //Set the subject of the message
            messageHelper.setSubject("notice-Evening meeting");
            //Set the content of the message
            messageHelper.setText("<b style='color:red'>Today 7:30 attend a meeting</b>",true);
            messageHelper.addAttachment("1.jpg", new File("C:\\wallpaper\\9.jpg"));
            //Set the sending account
            messageHelper.setFrom("123@qq.com");
            //Set the received mailbox
            messageHelper.setTo("456@163.com");
    
            mailSender.send(mimeMessage);
        }
    
    }
    

Keywords: Java Spring Spring Boot

Added by michaewlewis on Tue, 18 Jan 2022 19:55:10 +0200