【WEEK15】 【DAY1】Asynchronous Tasks【English Version】

2024.6.3 Monday

17. Asynchronous, Timed, and Email Tasks

In our work, we often need to handle asynchronous tasks. For example, when sending an email on a website, the backend sends the email while the frontend might become unresponsive until the email is sent, causing a delay in the response. To manage these tasks, we generally use multithreading. There are also timed tasks, such as analyzing the previous day’s log information at midnight. Additionally, there’s email sending—did you know that the predecessor of WeChat was also an email service? How are these things implemented? Actually, SpringBoot provides us with the corresponding support. It’s very easy to get started; we just need to enable some annotation support and configure some configuration files! Let’s take a look~

17.1. Asynchronous Tasks

17.1.1. Create a new springboot-09-test project

Insert image description here
When creating a project, if you encounter “Initialization failed for ‘https://start.spring.io/’ Please check URL, network, and proxy settings,” the solution is: 【Spring Common Errors】Initialization failed for ‘https://start.spring.io‘-Aliyun Developer Community (aliyun.com)
Insert image description here
Add Maven support (click the plus sign in Project Structure->Modules to add the corresponding project), conventionally modify the Maven, JDK, and Java version in settings, and the JDK and Java version in Project Structure. Update the Spring Framework version in pom to 2.7.13, add Thymeleaf dependency in pom.xml, and reload Maven.
Remove unnecessary files.

17.1.2. Create a service package

17.1.2.1. Create a class AsyncService

Insert image description here

Asynchronous processing is very common. For instance, when sending an email on a website, the backend handles the email sending, causing the frontend to be unresponsive until the email is sent. Therefore, we usually use multithreading to handle these tasks. Write a method that pretends to process data, use a thread to set some delay, simulating a synchronous wait situation:

package com.P51.service;

import org.springframework.stereotype.Service;

@Service
public class AsyncService {
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("Processing data");
    }
}

17.1.3. Create a controller package

17.1.3.1. Create an AsyncController class
package com.P51.controller;

import com.P51.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;

    @RequestMapping("/hello")
    public String hello(){
        asyncService.hello();   // Wait for three seconds
        return "finished";
    }
}

17.1.4. Run Springboot09TestApplication.java

【Synchronous Wait】 Run http://localhost:8080/hello and wait for three seconds before “finished” is displayed on the webpage, while “Processing data” is printed in the console.
Insert image description here

Insert image description here
Insert image description here

Problem: If we want users to get a message immediately, we can handle it in the background using multithreading. However, manually implementing multithreading each time is too cumbersome. We can simply use an easy method: add a simple annotation to our method.

17.1.5. Modify Springboot09TestApplication.java

package com.P51;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

// Enable asynchronous annotation functionality
@EnableAsync
@SpringBootApplication
public class Springboot09TestApplication {

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

}

17.1.6. Modify AsyncService.java

package com.P51.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {
    // Tell Spring this is an asynchronous method
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("Processing data");
    }
}

17.1.7. Restart Springboot09TestApplication.java

【Asynchronous Task】 Run http://localhost:8080/hello to immediately display “finished” on the webpage. After three seconds, “Processing data” is printed in the console.
Insert image description here
Insert image description here

  • 9
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值