티스토리 뷰

개발

Spring Async 를 이용한 비동기 처리

달리는개발자 2019. 7. 10. 14:19

스프링 문서 중에 Task Execution and Scheduling 을 이용하면 비동기 작업과 스케줄링 작업을 쉽게 구현할 수 있다.

https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#scheduling

 

Integration

As a lightweight container, Spring is often considered an EJB replacement. We do believe that for many, if not most, applications and use cases, Spring, as a container, combined with its rich supporting functionality in the area of transactions, ORM and JD

docs.spring.io

문서에서 보듯 TaskExecutor는 java.util.concurrent.Executor랑 동일하다

Springframework에서 다양한 TaskExecutor 구현체가 있는데 기본적으로 Executor Bean이 애플리케이션 컨텍스트에 없는 경우 SimpleAsyncTaskExecutor를 사용하는데 Thread를 재사용을 하지 않고 매번 생성하는 단점이 있다.

보통 실무에서 사용하는 것이 ThreadPoolTaskExecutor이다.

아래 소스는 Spring Boot 2.1.3.RELEASE 을 이용한 테스트 케이스이다

여러개의 ThreadPoolTaskExecutor를 선언하고 비동기 작업에 사용할 Executor를 지정할 수 있다.

꼭 알아두어야 될 것은 @EnableAsync, @Async로 인해 비동기 작업이 쉽다고 단순하게 썼다가 실무에서 OOME을 볼 수도 있다는 사실을 명심하고 ThreadPoolTaskExecutor 를 사용하자

가끔 아래와 같이 Bean으로 생성할 때 initialize()를 호출해서 수동으로 초기화 해주는 경우가 있는데 property 값들이 적용되고 고 afterPropertiesSet 에서 초기화를 하기 때문에 불필요한 호출이다. 그러지 말자.

 

참고

https://www.baeldung.com/spring-async

 

How To Do @Async in Spring | Baeldung

How to enable and use @Async in Spring - from the very simple config and basic usage to the more complex executors and exception handling strategies.

www.baeldung.com

 

반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함