在Java應用中,絕大多數狀況下都是經過同步的方式來實現交互處理的;可是在處理與第三方系統交互的時候,容易形成響應遲緩的狀況,以前大部分都是使用多線程來完成此類任務。java
其實,在Spring 3.x以後,就已經內置了@Async來完美解決這個問題。web
兩個註解:@EnableAysnc、@Aysncspring
使用異步任務的方式很簡單,只需:多線程
建立一個web項目。app
package com.zhaoyi.cweb.service; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class HelloService { public void doSomething(){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } }
package com.zhaoyi.cweb.controller; import com.zhaoyi.cweb.service.HelloService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @Autowired HelloService helloService; @GetMapping("/hello") public String hello(){ helloService.doSomething(); return "hello"; } }
顯然,咱們訪問/hello的話,要等待3秒才能得到結果。由於 doSomething方法佔用了太多的時間。異步
package com.zhaoyi.cweb; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @EnableAsync @SpringBootApplication public class CwebApplication { public static void main(String[] args) { SpringApplication.run(CwebApplication.class, args); } }
package com.zhaoyi.cweb.service; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class HelloService { @Async public void doSomething(){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } }
接下來咱們運行項目,訪問一樣的地址就能夠立馬獲得反饋了。測試
異步任務會被java單獨開啓的線程執行,從而保證不阻塞原進程。.net