说明:在Springboot项目中,使用@Async注解其实很简单,其作用就是在调用方法时加上这个注解,该方法的调用就变成了异步,无需等待执行完成,即可执行后续的代码逻辑。
使用:
1.首先pom文件引入必要的依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<dependencies>
<!-- SpringBoot 核心组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
</dependencies>
- springboot的启动类上添加注解@EnableAsync
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
@ComponentScan(basePackages = { "com.xwj.controller", "com.xwj.service" })
@EnableAsync //开启异步调用
@EnableAutoConfiguration
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
- 写一个方法加上@Async注解
@Service
public class TestService {
@Async
public void getLong() {
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
- 然后在接口调用他
@PostMapping(value = "list", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseResult getPageList() {
long start = System.currentTimeMillis();
testService.getLong();
System.out.println(System.currentTimeMillis() - start);
return ResponseResult.success();
}
- 最后查看打印结果
结论:如果是正常调用,应该会打印出9000+,但是使用@Async后,就可以实现异步调用,提高接口响应速度
注意:@Async注解所在方法一定不能和调用方处在同一个类下,不然失效!