본문 바로가기
프로젝트/AnswerDev

[AnswerDev] 4. @Async 비동기 처리와 Security Context

by kim-dev 2024. 8. 17.
반응형

 

나는 가능한 한 모든 기능을 비동기로 구현하고 있다.
어찌됐건 비동기로 처리하는 게 항상 빠르니까... 오류가 나면 처리하는 식으로 하고 있다.

 

그런데 여기서 문제는 @Async 비동기 처리를 사용하면, 각 작업마다 새로운 스레드를 만들어서 동작하기 때문에 하나의 스레드에서 만든 Security Context에 다른 스레드는 접근할 수 없다.

그래서 현재 접속 정보인 Authentication 데이터에 접근할 수 없는 문제가 있었다.

 

그러면 어떻게 해줘야 할까?

스레드 사이에서 Security Context를 공유할 수 있는 스레드 Executor인 DelegatingSecurityContextAsyncTaskExecutor을 사용해서 스레드 풀을 만들어주면 된다.

// AsyncConfig.java

@EnableAsync
@Configuration
public class AsyncConfig implements AsyncConfigurer {
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("AsyncExecutor-");
        executor.initialize();

        return new DelegatingSecurityContextAsyncTaskExecutor(executor);
    }
}

난 대충 이런 식으로 구현해 줬는데 제대로 동작하는 것을 확인할 수 있었다.