스프링 부트에서 @Async annotation을 적용함으로써 비동기 처리를 쉽게 할 수 있습니다.
@Async 사용법
1. @EnableAsync로 @Async를 쓰겠다고 스프링에게 알린다.
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(8);
executor.setMaxPoolSize(8);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("seung-pool-");
executor.initialize();
return executor;
}
}
- @EnableAsync : spring의 메서드의 비동기 기능을 활성화해준다.
- ThreadPoolTaskExecutor로 비동기로 호출하는 Thread 대한 설정을 한다.
- corePoolSize: 기본적으로 실행을 대기하고 있는 Thread의 개수
- MaxPoolSise: 동시 동작하는, 최대 Thread 개수
- QueueCapacity : MaxPoolSize를 초과하는 요청이 Thread 생성 요청 시 해당 내용을 Queue에 저장하게 되고, 사용할 수 있는 Thread 여유 자리가 발생하면 하나씩 꺼내져서 동작하게 된다.
- ThreadNamePrefix: spring이 생성하는 스레드의 접두사를 지정한다.
2. 비동기로 수행되었으면 하는 메서드 위에 @Async를 적용한다.
public class AsyncService {
private static final Logger logger = LoggerFactory.getLogger(AsyncService.class);
//비동기로 동작하는 메소드
@Async
public void onAsync(int i) {
logger.info("onAsync i=" + i);
}
}
@RestController
public class AsyncController {
@Autowired
private AsyncService service;
@GetMapping("/async")
public String goAsync() {
for(int i=0;i<1000;i++) {
service.onAsync(i);
}
String str = "Hello Spring Boot Async!!";
return str;
}
}
브라우저에서 "localhost:8080/async"로 요청을 하면 로그가 1,000번 찍는 과정이 비동기로 호출되는 것을 확인할 수 있습니다.
스레드 접두사가 "seung-pool-"로 고정되었고, 비동기 작업 시 다른 스레드를 사용하는 것을 알 수 있습니다.
※ 주의 사항은 다음과 같습니다.
- private은 안된다. 반드시 public으로 메서드를 선언한다.
- 같은 클래스의 메서드에 @Async 설정하여 호출할 경우 동작하지 않는다.
참고 :
https://spring.io/guides/gs/async-method/
Creating Asynchronous Methods
this guide is designed to get you productive as quickly as possible and using the latest Spring project releases and techniques as recommended by the Spring team
spring.io
https://www.hanumoka.net/2020/07/02/springBoot-20200702-sringboot-async-service/
springboot 비동기 서비스 만들기(Async)
들어가기springboot rest 서버에서 어떤 요청을 받으면, Shell command를 호출하는 기능을 구현해야 한다. 문제는 Shell command로 호출하는 호출하는 것이 Python 스크립트이고, 이 스크립트 동작이 몇분은
www.hanumoka.net
https://jeong-pro.tistory.com/187
How does @Async work? @Async를 지금까지 잘 못 쓰고 있었습니다(@Async 사용할 때 주의해야 할 것, 사용법
@Async in Spring boot 스프링 부트에서 개발자에게 비동기 처리를 손쉽게 할 수 있도록 다양한 방법을 제공하고 있다. 대세는 Reactive stack, CompletableFuture를 쓰겠으나 역시 가장 쉬운 방법으로는 @Async..
jeong-pro.tistory.com
전체 소스
https://github.com/keepseung/SpringBoot-Blog-Source/tree/main/async
GitHub - keepseung/SpringBoot-Blog-Source: 스프링 부트를 사용해 어플리케이션을 만들때 필요한 기능들을
스프링 부트를 사용해 어플리케이션을 만들때 필요한 기능들을 담고 있습니다. . Contribute to keepseung/SpringBoot-Blog-Source development by creating an account on GitHub.
github.com
'스프링 > Spring' 카테고리의 다른 글
@SessionAttribute 어노테이션을 사용해서 세션 조회하기 (0) | 2021.10.26 |
---|---|
[SpringBoot] 서블릿의 HttpSession을 사용해 세션 구현하기 (0) | 2021.10.26 |
[SpringBoot] 스프링부트에서 스케쥴러 사용하기 (0) | 2021.10.24 |
Rabbitmq + SpringBoot 샘플 프로젝트 만들기 (0) | 2021.10.16 |
RabbitMQ 설치하기 (0) | 2021.10.16 |