|
| 1 | +package com.semosan.api.domain.notification.dispatcher; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 4 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 5 | +import com.google.firebase.messaging.FirebaseMessagingException; |
| 6 | +import com.google.firebase.messaging.MessagingErrorCode; |
| 7 | +import com.semosan.api.common.fcm.FcmService; |
| 8 | +import com.semosan.api.domain.notification.service.FcmTokenService; |
| 9 | +import lombok.RequiredArgsConstructor; |
| 10 | +import lombok.extern.slf4j.Slf4j; |
| 11 | +import org.springframework.scheduling.annotation.Async; |
| 12 | +import org.springframework.stereotype.Component; |
| 13 | + |
| 14 | +import java.util.HashMap; |
| 15 | +import java.util.Map; |
| 16 | + |
| 17 | +@Slf4j |
| 18 | +@Component |
| 19 | +@RequiredArgsConstructor |
| 20 | +public class AsyncNotificationDispatcher implements NotificationDispatcher { |
| 21 | + |
| 22 | + private final FcmService fcmService; |
| 23 | + private final FcmTokenService fcmTokenService; |
| 24 | + private final ObjectMapper objectMapper; |
| 25 | + |
| 26 | + /** |
| 27 | + * @Async 가 같은 클래스에 있는 함수를 호출 할 때는 비동기로 작동하지 않으니 주의해야함 |
| 28 | + * AOP 프록시를 사용해서 그렇고, 그래서 빈으로 등록된 다른 클래스에서 호출해야함 |
| 29 | + */ |
| 30 | + @Override |
| 31 | + @Async("notificationTaskExecutor") |
| 32 | + public void dispatch(NotificationDispatchCommand cmd) { |
| 33 | + Map<String, String> dataPayload = buildDataPayload(cmd); |
| 34 | + |
| 35 | + for (String token : cmd.tokens()) { |
| 36 | + try { |
| 37 | + fcmService.sendMessage(token, cmd.title(), cmd.body(), dataPayload); |
| 38 | + } catch (FirebaseMessagingException e) { |
| 39 | + handleSendError(token, e); |
| 40 | + } catch (Exception e) { |
| 41 | + log.error("FCM 발송 중 알 수 없는 에러 (token={}): {}", token, e.getMessage(), e); |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + private Map<String, String> buildDataPayload(NotificationDispatchCommand cmd) { |
| 47 | + Map<String, String> data = new HashMap<>(); |
| 48 | + data.put("type", cmd.type().name()); |
| 49 | + data.put("notificationId", String.valueOf(cmd.notificationId())); |
| 50 | + try { |
| 51 | + data.put("extras", objectMapper.writeValueAsString(cmd.extras())); |
| 52 | + } catch (JsonProcessingException e) { |
| 53 | + log.error("extras 직렬화 실패", e); |
| 54 | + data.put("extras", "{}"); |
| 55 | + } |
| 56 | + return data; |
| 57 | + } |
| 58 | + |
| 59 | + private void handleSendError(String token, FirebaseMessagingException e) { |
| 60 | + MessagingErrorCode code = e.getMessagingErrorCode(); |
| 61 | + if (code == MessagingErrorCode.UNREGISTERED || code == MessagingErrorCode.INVALID_ARGUMENT) { |
| 62 | + log.warn("만료/잘못된 토큰 삭제 (token={}, code={})", token, code); |
| 63 | + fcmTokenService.deleteExpired(token); |
| 64 | + } else { |
| 65 | + log.error("FCM 발송 실패 (token={}, code={}): {}", token, code, e.getMessage()); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments