Spring Boot is a new framework provided by the Pivotal team. It is designed to simplify the initial construction and development process of new Spring applications. The framework uses an ad hoc approach to configuration, eliminating the need for developers to define boilerplate configurations. To understand it in my own words, Spring Boot is actually not a new framework. It configures the use of many frameworks by default, just like Maven integrates all Jar packages and Spring Boot integrates all frameworks.
1) Create an independent Spring application;
2) Directly embed Tomcat, Jetty or Undertow without deploying a WAR file;
3) Provide recommended basic POM files (starters) to simplify Apache Maven configuration;
4) Automatically configure the Spring framework according to project dependencies as much as possible;
5) Provide direct Features used in production environments, such as performance indicators, application information and application health checks;
6) are available out of the box, no code generation, and no need to configure too much xml. The default values can also be modified to meet specific needs.
7) A large number of other projects are based on Spring Boot, such as Spring Cloud.
Example:
Write a hello method in the service and delay it for three seconds
@Service public class AsyncService { public void hello(){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("数据正在处理!"); } }
Let the Controller call this business
@RestController public class AsyncController { @Autowired AsyncService asyncService; @GetMapping("/hello") public String hello(){ asyncService.hello(); return "ok"; } }
When we start the SpringBoot project, we will find that it will respond ok after three seconds.
So we need to use asynchronous tasks to solve this problem. It is very simple to add an annotation.
@Async annotation on the hello method
@Service public class AsyncService { //异步任务 @Async public void hello(){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("数据正在处理!"); } }
Enable the asynchronous annotation function on the SpringBoot startup class
@SpringBootApplication //开启了异步注解的功能 @EnableAsync public class Sprintboot09TestApplication { public static void main(String[] args) { SpringApplication.run(Sprintboot09TestApplication.class, args); } }
The problem is solved, the server will respond to the front-end data instantly!
The more the tree yearns for the light at high places, the more its roots will move downward, toward the soil and into the depths of darkness.
The above is the detailed content of How to implement asynchronous tasks in springboot. For more information, please follow other related articles on the PHP Chinese website!