本文中使用的spring版本是 4.3.10 release版,爲此時最新發布版.html
本文中的內容在spring文檔的34章4節,地址爲 http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#scheduling-annotation-support-exception.java
##使用java配置開啓異步支持spring
@Configuration @EnableAsync @EnableScheduling public class AppConfig { }
@Configuration 標誌這是一個spring的配置類異步
@EnableAsync 標誌異步支持開始.net
@EnableScheduling 標誌着定時任務開始線程
##使用xml開始異步支持code
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"> <task:annotation-driven executor="myExecutor" scheduler="myScheduler"/> <task:executor id="myExecutor" pool-size="5"/> <task:scheduler id="myScheduler" pool-size="10"/> </beans>
設置了task的執行器,id爲'myExecutor',線程池容量爲5;xml
設置了定時任務的執行器,id爲'myScheduler',線程池容量爲10;htm
在事件中使用異步方法進程
@EventListener @Async public void handleEvent2(EventEvent event) { System.out.println("異步輸出問題!!"); }
@EventListener,標誌這是一個事件監聽器
@Async 標誌這是一個異步方法,該方法將做爲守護進程運行.
通常異步方法的返回值應該是java.util.concurrent.Future類型或 Spring 4.2新增的 org.springframework.util.concurrent.ListenableFuture 還有JDK 8的 java.util.concurrent.CompletableFuture類型
目前spring的事件異步處理方法不支持任何返回值.