저번에 회사에서 애플의 apns를 이용해 각각 애플 디바이스로 푸시를 할 수 있는
기능을 만들었습니다.
알람기능은 굳이 “동기“방식으로 구현할 필요가 없었기 때문에 “비동기“방식으로
구현했고, 그때 사용한것이 @Async 어노테이션이었습니다.
@Async에 대한 레퍼런스 문서는 링크를 참조하시면 됩니다.
사용방법은 무척이나 간단합니다.
1. 먼저 비동기로 실행할 놈을 빈으로 설정합니다.
<task:executor id="testExecutor" pool-size="10"/> <task:annotation-driven executor="testExecutor"/>
pool-size는 각각 상황에 맞게 적절하게 지정해주시면 됩니다.
2. @Async 어노테이션을 비동기로 실행할 메서드에 붙여줍니다.
이때 주의할 점은 @Async 어노테이션이 붙은 메서드의 리턴타입은 void 혹은
java.util.concurrent.Future타입이라는 것입니다.
다른 타입으로 지정시 무조건 null이 넘어오므로 주의해야 합니다.
@Async public Future<Integer> test() { System.out.println("==========================="); System.out.println("test메서드 실행###"); System.out.println("==========================="); return new AsyncResult<Integer>(-2); }
마지막으로 간단한 테스트케이스를 작성해 보았습니다.
@Test public void async_리턴값확인() throws InterruptedException, ExecutionException { assertThat(asyncTest.test().get(), is(-2)); }
해당 테스트를 실행하면, 에러없이 결과가 출력됨을 확인할 수 있습니다.
*참고 url
- http://whiteship.tistory.com/2503
- http://whiteship.tistory.com/2590
- 토비의 스프링3 p.1370