最近在開發過程裏遇到讓人很頭痛的功能,就是一個批量複製功能,批量複製中包括數據庫中的數據,還有文件系統的複製。這在開發中要考慮到系統性能和友好度的問題,一個批量複製最少要執行1~3分鐘,這讓用戶在點擊一個按鈕後要等待1~3分鐘不現實,最後只能用多線程,來達到用戶的友好度。
在項目既然用到了Spring ,我們用Spring實現的多線程來實現這個功能。
public class JobUtilsTest{
@Autowired
private DaoService service;
@Test
public void testAsync() throws Exception {
System.out.println("start" );
service.update(); // ★ 假設這個方法會比較耗時,需要異步執行
System.out.println("end");
Thread.sleep(3000); // 因爲junit結束會結束jvm,所以讓它等會異步線程
}
}
在方法上加@Async註解 這個方法就成異步方法了
異步方法不能和調用方法放在一個類裏面
@Service
public class DaoService {
@Async
public void update() {
try {
Thread.sleep(2000);
// do something
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("operation complete.");
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<context:component-scan base-package="com.chinacache" />
<!--Spring 的配置文件中一定要配置這一項 -->
<task:annotation-driven/>
</beans>
輸出結果:
start
end
operation complete.