
알림 서비스 kafak Consumer의 메시지 소비 및 전송 로직에 전략(Strategy)패턴을 도입하여 구조를 개선.
기존에는 Kafka Consumer에서 직접 이벤트Dto 역직렬화, 메세지 생성, 알림(Slack) 전송, 예외 처리를 모두 수행했음.
전략(Strategy)패턴으로 AlertContext와 AlertStrategy를 활용하여 해당 로직을 분리하여 리팩토링.
AlertStrategy인터페이스와 이를 구현한 AchievementStrategy, CompetitionStrategy를 추가하여 이벤트 발생 유형에 따라 각각 메시지 생성, 예외 처리를 담당.
AlertContext는 전체적인 메서드 실행 흐름을 구성하여 상황에 맞는 Strategy구현체만 주입받아 실행하도록 리팩토링하여 코드중복 제거와 새로운 이벤트 타입이 생길시 확장성 향상.
컨슈머에서 받은 DTO를 역직렬화하는 과정에서 이벤트발생 유형마다 받는 EventDto의 형식이 달라 이를 제네릭으로 받아서 역직렬화 처리를 구현.
하지만 런타임시 타입 이레이저로 인해 제네릭 T의 정보가 사라져 제네릭을 어떻게 사용해야할지 문제가 있었음.
역직렬화시 이벤트Dto의 클래스 정보도(Class<T>)함께 Context에 넘겨주도록 구현하여 간단히 문제 해결.
@Component
@RequiredArgsConstructor
public class AlertContext<T> {
private final ObjectMapper objectMapper;
private final MessageService messageService;
public void sendMessage(Map<String, Object> eventMap, AlertStrategy<T> alertStrategy, Class<T> clazz) {
try {
T dto = objectMapper.convertValue(eventMap, clazz);
String message = alertStrategy.makeMessage(dto);
messageService.sendMessage(message, alertStrategy.getMediaId(dto));
}catch (Exception e) {
alertStrategy.throwException(e);
}
}
}