Spring 3.0 : Webで非同期処理を実行する。
計算に時間がかかる場合、まずHTTPレスポンスを返してしまって、裏でじっくりやりたい、という場合の設定方法です。相変わらず、自分宛メモ。
<dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version> </dependency>
- applicationContext.xmlに設定を追加
- task ネームスペースの設定と task:annotation-drivenを設定します。
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <beans xmlns="http://www.springframework.org/schema/beans" ... xmlns:task="http://www.springframework.org/schema/task" ... xsi:schemaLocation="... http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"> .. <task:annotation-driven/> </beans>
- 非同期に実行したいサービスメソッドに@Async アノテーションをつける
@Controller public class MyController{ @Autowired private MyService service; @RequestMapping(method=RequestMethod.POST) public String post(){ //このメソッドを非同期に実行したい場合 service.asyncMethod(); return "redirect:/page"; } } @Service public class MyService{ // アノテーションつけるだけでオーケー @Async public void asyncMethod(){ ... }
簡単でしたよ。やるなあ。