說明:在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註解所在方法一定不能和調用方處在同一個類下,不然失效!