Kim ByeungHyun
@Async annotation 비동기처리 본문
@Async는 spring에서 제공하는 Thred Pool을 활용하는 비동기 메소드 지원 어노테이션이다.
비동기로 작동하길 원하는 method위에 @Async를 붙여주면 사용할 수 있다.
@Async
public void send(Member receiver, AlarmType alarmType, String message, Long articlesId, String title) {
Notification notification = notificationRepository.save(createNotification(receiver, alarmType, message, articlesId, title));
String receiverId = String.valueOf(receiver.getMemberId());
String eventId = receiverId + "_" + System.currentTimeMillis();
Map<String, SseEmitter> emitters = emitterRepository.findAllEmitterStartWithByUserId(receiverId);
emitters.forEach(
(key, emitter) -> {
emitterRepository.saveEventCache(key, notification);
NotificationResponseDto notificationResponseDto = new NotificationResponseDto(notification);
sendToClient(emitter, eventId, notificationResponseDto);
}
);
}
장점 :
개발자는 메소드를 동기 방식으로 작성하다가, 비동기 방식을 원한다면 단순히 @Asyns어노테이션을 메소드 위에 붙여 주면 된다. 그래서 동기, 비동기에 대해 유지보수가 좋은 코드를 만들수 있다.
주의사항 :
@Async 기능을 사용하기 위해서는 @EnablAsync 어노테이션을 선언하는데,
이때 별도의 설정을 하지 않으면 프록시 모드로 동작한다.
즉, @Async 어노테이션으로 동작하는 비동기 메소드는 모두 스프링 AOP의 제약사항을 그대로 따르게 된다.
- private 메서드에 @Async를 붙여도 AOP가 동작하지 않는다.
- 같은 객체 내의 메소드까지 호출 할 시 AOP가 동작하지 않는다.
+AOP 참고
https://steady-coding.tistory.com/608
참고
https://steady-coding.tistory.com/611