스프링 - 비동기 2 (구현)

산하·2021년 12월 15일
0

Spring

목록 보기
5/6
post-thumbnail

mail 알림을 구현하면서 응답 지연 이슈가 있었다.
사용자에게 알림 메일을 발송해야 했는데 메일 발송이 끝날 때 까지 클라이언트가 응답을 받지 못해 처리가 늦어지는 문제가 발생했다.


스프링이 아주 다 해줘서 구현하는 데 어려움은 별로 없었다!


Thread pool의 수를 고민했지만 메일이 많이 쌓일 것 같지 않고 바로 메일이 전송될 필요도 없어서 queue size만 크게 잡고 thread pool의 수는 정말 최소한만 뒀다.


AsyncConfig.java

@Configuration // 설정 
@EnableAsync // spring 메소드 비동기 기능 활성화
public class AsyncConfig extends AsyncConfigurerSupport{

	@Override
	public Executor getAsyncExecutor(){
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		//기본적으로 실행 대기하는 thread의 갯수 설정
		executor.setCorePoolSize(2);
		//동시동작하는 최대 Thread pool 크기
		executor.setMaxPoolSize(10);
		//thread pool que 크기
		executor.setQueueCapacity(500);
		// spring이 생성하는 thread의 접두사 설정
		executor.setThreadNamePrefix("mail-async-");
		//initialize 안해주면 executor 사용 불가
		executor.initialize();
		return executor;
	  }
}

MailService.java


@Async
public void assessmentMailBuilder(MailDtomailDto) throws MessagingException{
	//서비스 로직
}

AsyncConfigurerSupport

AsyncConfigurer를 구현할 때 상속 받는 class

getAsyncExecutor()

  • Executor 메소드를 호출하여 비동기 처리를 할 때 이 메소드를 오버라이드 하여 thread pool 등을 재설정 가능

ThreadPoolTaskExecutor

setCorePoolSize

  • ThreadPoolExecutor의 코어 풀 크기 설정
  • 기본적으로 관리할 Thread 숫자

setMaxPoolSize

  • core pool과 queue가 다 찼을 때 최대로 생성할 Thread 숫자
  • 기본값은 Integer.MAX_VALUE

setQueueCapacity

  • core pool이 다 찼을 때(core pool의 크기를 넘어서는 tesk가 들어왔을 때) tesk가 쌓일 수 있는 갯수

@Async

  • 비동기 처리를 하고자 하는 메소드 위에 추가
  • 지정된 비동기 작업을 위한 어노테이션
profile
반갑습니다 :) 백앤드 개발자 산하입니다!

0개의 댓글