Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
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
Tags
more
Archives
Today
Total
관리 메뉴

Kim ByeungHyun

@Async annotation 비동기처리 본문

카테고리 없음

@Async annotation 비동기처리

sandbackend 2022. 12. 10. 19:23

@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://dzone.com/articles/effective-advice-on-spring-async-part-1

 

 

 

 

참고

https://velog.io/@gillog/Spring-Async-Annotation%EB%B9%84%EB%8F%99%EA%B8%B0-%EB%A9%94%EC%86%8C%EB%93%9C-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0

https://steady-coding.tistory.com/611