主要记录内容:
在springboot中如何开启异步注解功能,异步注解功能开启后,可以让在调用异步功能时,系统可以自动接着往下走,而不用一直在等待异步功能完成才可以接着走下一步任务。
前提:内容时基于springboot实现的。
一、service层代码:在service中定义了一个测试异步的代码:在方法上增加@Async注解
package com.demo.service; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class AsyncService { // @Async 告诉spring 这个一个异步方法 @Async public void hello(){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("数据处理中....."); } }
二、springboot默认是不开启异步注解功能的,所以,要让springboot中识别@Async,则必须在入口文件中,开启异步注解功能
package com.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; //开启异步注解功能 @EnableAsync @SpringBootApplication public class SpringbootTaskApplication { public static void main(String[] args) { SpringApplication.run(SpringbootTaskApplication.class, args); } }
三、这样,当在controller层中调用service层的异步方法时,方法会异步进行,前端不会一直处于等待中
package com.demo.controller; import com.demo.service.AsyncService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class AsyncController { @Autowired AsyncService asyncService; @GetMapping("/hello") public String hello() { this.asyncService.hello();//停止三秒 return "success"; } }