ApplicationEventPublisher
가 처리한다.@RequiredArgsConstructor
@Service
public class MakeMatchAndMessageRoom {
private final MatchService matchService;
private final MessageRoomService messageRoomService;
private final ApplicationEventPublisher eventPublisher;
@Transactional
public MessageRoomDto execute(Member fromMember, Member toMember) {
Match newMatch = matchService.createMatch(fromMember, toMember);
MessageRoom newMessageRoom = messageRoomService.createMessageRoom(fromMember, toMember, newMatch);
MessageRoomDto messageRoomDto = MessageRoomDto.from(newMessageRoom);
notifyMatch(messageRoomDto.matchDto(), messageRoomDto);
return messageRoomDto;
}
private void notifyMatch(MatchDto matchDto, MessageRoomDto messageRoomDto) {
eventPublisher.publishEvent(new MatchEvent(this, matchDto, messageRoomDto));
}
}
코드에서처럼 ApplicationEventPublisher를 주입받고, publishEvent만 호출하면 된다. 이때 publishEvent에는 발생시키고자 하는 ApplicationEvent 상속 객체를 전달하면 된다.
프로젝트에서는 MatchEvent클래스를 작성했다.
@Getter
public class MatchEvent extends ApplicationEvent {
private final MatchDto match;
private final MessageRoomDto messageRoom;
public MatchEvent(MakeMatchAndMessageRoom source, MatchDto newMatch, MessageRoomDto messageRoom) {
super(source);
this.match = newMatch;
this.messageRoom = messageRoom;
}
}
@Component
@RequiredArgsConstructor
public class MatchEventListener {
private final SseService sseService;
private final MatchNotificationRepository matchNotificationRepository;
@EventListener
@Transactional(propagation = Propagation.REQUIRES_NEW)
@Async
public void sendMatchNotification(MatchEvent matchEvent) {
(생략)
sseService.send(matchEvent.getMatch().toMember().id(), notificationResponse);
sseService.send(matchEvent.getMatch().fromMember().id(), notificationResponse);
}
}