Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BE] 입장 10분 전 푸시 알림 전송 기능 구현 (#483) #484

Closed
wants to merge 47 commits into from
Closed
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
cbcad44
feat: 입장 알림 전송 기능 구현
xxeol2 Oct 1, 2023
21f86ff
refactor: FCMClient 인터페이스화
xxeol2 Oct 2, 2023
4c17ab6
refactor: 스케쥴링 중복 실행시 409 Conflict
xxeol2 Oct 2, 2023
2e4530d
refactor: entryAlert 비관적락 적용
xxeol2 Oct 2, 2023
4a77dd7
refactor: EntryAlertEventListener에서 EntryAlertRepository 참조 제거
xxeol2 Oct 2, 2023
690f90f
refactor: FCM Aycnc Config 정의
xxeol2 Oct 2, 2023
323c6d9
feat: flyway script 작성
xxeol2 Oct 2, 2023
1651604
feat: MockFcmClient 생성
xxeol2 Oct 2, 2023
3b308b5
refactor: FCMNotificationEventListener Async 빈 지정
xxeol2 Oct 2, 2023
97daba8
feat: SpringBoot 실행시 initSchedule
xxeol2 Oct 2, 2023
aa4e530
refactor: Async ThreadPool 하나만 활용하도록 수정
xxeol2 Oct 2, 2023
44ced57
test: FcmClientImplTet 작성
xxeol2 Oct 2, 2023
bd7451b
feat: MemberFcmFixture 정의
xxeol2 Oct 2, 2023
221cac0
refactor: findAllTokenByMemberIdIn 메서드 활용
xxeol2 Oct 2, 2023
a083e3c
style: 패키지 네이밍 수정 (entry_alert -> entryalert)
xxeol2 Oct 2, 2023
6aebcd5
refactor: 500건만 전송하도록 하는 로직 FcmClientImpl로 이동
xxeol2 Oct 4, 2023
da70c4d
refactor: fcmToken String으로 추출
xxeol2 Oct 4, 2023
4c20e30
refactor: ApplicationReadyEvent Listener 최상단으로 이동
xxeol2 Oct 4, 2023
03588d1
refactor: taskScheduler에 람다식으로 넘겨주도록 리팩토링
xxeol2 Oct 4, 2023
64759af
refactor: EntryAlert에 AlertStatus 추가
xxeol2 Oct 4, 2023
a29ae79
refactor: FCM 전송시 데드락 문제 해결
xxeol2 Oct 4, 2023
49c15e6
refactor: AsyncBatch 템플릿 콜백 패턴 적용
xxeol2 Oct 4, 2023
e253317
refactor: Async ThreadPool설정 클래스 위치 이동
xxeol2 Oct 4, 2023
78e5820
refactor: EntryAlertResultHandler 네이밍 수정
xxeol2 Oct 4, 2023
7b4a210
refactor: fcmExecutor QueueCapacity 기본값으로 수정
xxeol2 Oct 4, 2023
fff1325
feat: flyway 추가
xxeol2 Oct 4, 2023
6995f68
test: LocalDateTime 타임존 UTC로 수정
xxeol2 Oct 4, 2023
639e228
Merge remote-tracking branch 'origin/dev' into feat/#483
xxeol2 Oct 5, 2023
ac669fc
fix: EntryAlertServiceTest Mock 객체 수정
xxeol2 Oct 5, 2023
dd9d56f
refactor: test LocalDateTime 수정
xxeol2 Oct 5, 2023
828935c
Merge remote-tracking branch 'origin/dev' into feat/#483
xxeol2 Oct 5, 2023
26fed9f
test: EntryAlertRepositoryTest 작성
xxeol2 Oct 5, 2023
4577784
refactor: JPQL 파라미터 @Param 어노테이션 추가
xxeol2 Oct 5, 2023
44c583b
refactor: 빈 토큰 검사 메서드 네이밍 수정
xxeol2 Oct 5, 2023
a42051a
refactor: SENT/FAILED 상태 삭제
xxeol2 Oct 5, 2023
7d872a9
refcator: EntryAlert 스케쥴링 추가 로깅 자세하게 수정
xxeol2 Oct 5, 2023
310cd14
remove: 불필요한 유틸 클래스 삭제
xxeol2 Oct 5, 2023
ce2adf1
refactor: Test 의존성 추가
xxeol2 Oct 5, 2023
b081b35
refactor: FCmClient로 빈 토큰이 넘어오면 early return
xxeol2 Oct 5, 2023
40f9359
feat: EntryAlert 알림 전송 시작 로깅
xxeol2 Oct 5, 2023
8965022
fix: MockFcmClient Profile 수정
xxeol2 Oct 5, 2023
e374d66
refactor: FcmClientImpl Executor -> TaskExecutor로 수정
xxeol2 Oct 5, 2023
d1f1792
refactor: 접근제어자 변경 public -> private
xxeol2 Oct 5, 2023
6e06a21
refactor: 롬복 적용
xxeol2 Oct 5, 2023
94a3d55
refactor: EntryAlert request상태로 변경 메서드 네이밍 수정
xxeol2 Oct 5, 2023
e45fde3
refactor: sendEntryAlert에서 예외를 던지지 않는 방향으로 수정
xxeol2 Oct 5, 2023
e2b1eaa
refactor: graceful shutdown 설정
xxeol2 Oct 8, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.festago.common.exception;

public class ConflictException extends FestaGoException {

public ConflictException(ErrorCode errorCode) {
super(errorCode);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public enum ErrorCode {
DUPLICATE_STUDENT_EMAIL("이미 인증된 이메일입니다."),
TICKET_CANNOT_RESERVE_STAGE_START("공연의 시작 시간 이후로 예매할 수 없습니다."),
INVALID_STUDENT_VERIFICATION_CODE("올바르지 않은 학생 인증 코드입니다."),
INVALID_ENTRY_ALERT_TIME("올바르지 않은 입장 알림 시간입니다"),

// 401
EXPIRED_AUTH_TOKEN("만료된 로그인 토큰입니다."),
Expand All @@ -46,6 +47,9 @@ public enum ErrorCode {
TICKET_NOT_FOUND("존재하지 않는 티켓입니다."),
SCHOOL_NOT_FOUND("존재하지 않는 학교입니다."),

// 409
ALREADY_ALERT("이미 입장 알림이 전송되었습니다."),

// 500
INTERNAL_SERVER_ERROR("서버 내부에 문제가 발생했습니다."),
INVALID_ENTRY_CODE_PERIOD("올바르지 않은 입장코드 유효기간입니다."),
Expand Down
10 changes: 10 additions & 0 deletions backend/src/main/java/com/festago/config/SchedulingConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.festago.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@EnableScheduling
public class SchedulingConfig {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.festago.entry_alert.application;
xxeol2 marked this conversation as resolved.
Show resolved Hide resolved

import com.festago.entry_alert.dto.EntryAlertResponse;
import com.festago.ticket.dto.event.TicketCreateEvent;
import java.time.Clock;
import java.time.LocalDateTime;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

@Component
public class EntryAlertEventListener {

private static final Logger log = LoggerFactory.getLogger(EntryAlertEventListener.class);

private final EntryAlertService entryAlertService;
private final TaskScheduler taskScheduler;
private final Clock clock;

public EntryAlertEventListener(EntryAlertService entryAlertService, TaskScheduler taskScheduler, Clock clock) {
this.entryAlertService = entryAlertService;
this.taskScheduler = taskScheduler;
this.clock = clock;
}

@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
@Async
public void addEntryAlertSchedule(TicketCreateEvent event) {
EntryAlertResponse entryAlert = entryAlertService.create(event.stageId(), event.entryTime());
addSchedule(entryAlert);
}

private void addSchedule(EntryAlertResponse entryAlert) {
log.info("add entryAlert schedule: {}", entryAlert.id());
Runnable task = createEntryAlertTask(entryAlert.id());
LocalDateTime alertTime = entryAlert.alertTime();
taskScheduler.schedule(task, alertTime.atZone(clock.getZone()).toInstant());
}

private Runnable createEntryAlertTask(Long id) {
return () -> entryAlertService.sendEntryAlert(id);
}
xxeol2 marked this conversation as resolved.
Show resolved Hide resolved

@EventListener(ApplicationReadyEvent.class)
public void initEntryAlertSchedule() {
List<EntryAlertResponse> entryAlerts = entryAlertService.findAll();
entryAlerts.forEach(this::addSchedule);
}
xxeol2 marked this conversation as resolved.
Show resolved Hide resolved
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package com.festago.entry_alert.application;

import com.festago.common.exception.ConflictException;
import com.festago.common.exception.ErrorCode;
import com.festago.entry_alert.domain.EntryAlert;
import com.festago.entry_alert.dto.EntryAlertResponse;
import com.festago.entry_alert.repository.EntryAlertRepository;
import com.festago.fcm.application.FcmClient;
import com.festago.fcm.domain.FCMChannel;
import com.festago.fcm.domain.MemberFCM;
import com.festago.fcm.dto.FcmPayload;
import com.festago.fcm.repository.MemberFCMRepository;
import com.festago.ticketing.repository.MemberTicketRepository;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class EntryAlertService {

private static final int BATCH_ALERT_SIZE = 500;

private final EntryAlertRepository entryAlertRepository;
private final MemberTicketRepository memberTicketRepository;
private final MemberFCMRepository memberFCMRepository;
private final FcmClient fcmClient;

public EntryAlertService(EntryAlertRepository entryAlertRepository, MemberTicketRepository memberTicketRepository,
MemberFCMRepository memberFCMRepository, FcmClient fcmClient) {
this.entryAlertRepository = entryAlertRepository;
this.memberTicketRepository = memberTicketRepository;
this.memberFCMRepository = memberFCMRepository;
this.fcmClient = fcmClient;
}

@Transactional(readOnly = true)
public List<EntryAlertResponse> findAll() {
return entryAlertRepository.findAll().stream()
.map(alert -> new EntryAlertResponse(alert.getId(), alert.findAlertTime()))
.toList();
}

public EntryAlertResponse create(Long stageId, LocalDateTime entryTime) {
EntryAlert entryAlert = entryAlertRepository.save(new EntryAlert(stageId, entryTime));
return new EntryAlertResponse(entryAlert.getId(), entryAlert.findAlertTime());
}

@Async
public void sendEntryAlert(Long id) {
EntryAlert entryAlert = entryAlertRepository.findByIdForUpdate(id)
.orElseThrow(() -> new ConflictException(ErrorCode.ALREADY_ALERT));
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

참고 노션에도 언급되어있듯 동시에 2대의 WAS에서 실행할 때, 하나만 실행되고 나머지 하나는 예외처리가 되도록 했습니다!
그런데 이 때, BadRequest는 아닌 것 같고.. (클라이언트의 요청이 없으니)
InternalServerException은 로깅이 찍히고 그래서
아예 별도의 예외 객체가 필요할 것 같아서 따라서 ConflictException으로 처리했어요!
(사실 서버 내부적으로 동작하는거라 클라이언트에까지 응답이 내려갈 일은 없을 것 같아요)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

여기서 delete 하는 방법도 있지만 처리전, 처리후 같은 식의 상태를 변경시키는 방법은 어떨까요?

그렇게한다면 굳이 throw안하고, early return 하는 방법으로도 처리할 수도 있고
제대로 스케쥴링이 처리됐는지, 명시적으로 확인할 수도 있을 것 같아요.
데이터가 쌓인다는 점이 있지만 수백~수천개 정도의 데이터는 큰 문제가 안되고, 나중에 주기적으로 비워줄 수도 있으니까요.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

푸시알림 전송 여부를 추적할 수 있다는 점에서 오리가 말씀해주신 방법이 좋아보이네요!
해당 방법으로 수정해보겠습니다!!

List<Long> memberIds = memberTicketRepository.findAllOwnerIdByStageIdAndEntryTime(entryAlert.getStageId(),
entryAlert.getEntryTime());
List<String> tokens = memberFCMRepository.findAllByMemberIdIn(memberIds)
.stream()
.map(MemberFCM::getFcmToken)
.toList();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

class MemberFCMRepository {
    ...
    @Query("SELECT mf.fcmToken FROM MemberFCM mf WHERE mf.memberId in :memberIds")
    List<String> findAllTokenByMemberIdIn(@Param("memberIds") List<Long> memberIds);
    ...
}

다음과 같이 사용할 수 있을 것 같네요!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

반영 완료했습니다 👍

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

찾아보니 이런 방법도 있네요.
전 글렌 코멘트대로 JPQL로 처리하는게 더 간단하고 좋다고 합니다만, 그래도 알게되서 참고용으로 링크 걸어봅니다.
인덱스 컨디션 등으로 성능 최적화 시킬 부분이 많고 유지 보수가 어려운 특정 프로젝트에서는 관리 포인트를 편하게하기 위해 사용할 수 있을 것 같습니다.

https://stackoverflow.com/questions/22007341/spring-jpa-selecting-specific-columns

저희 프로젝트에서는 만약 적용한다면 이런식으로..(일케 하자는건 아니고 그냥 참고용입니당. 위에서 적은 것처럼 저희 프로젝트에서는 JPQL이 지금은 더 좋다고 생각해요.)

public interface FcmToken {

    String getFcmToken();
}

혹은 레코드

public record FcmToken(String fcmToken) {
}
 List<FcmToken> findTokenByMemberIdIn(List<Long> memberIds);

....

Hibernate: 
    select
        m1_0.fcm_token 
    from
        member_fcm m1_0 
    where
        m1_0.member_id in(?,?)

sendMessages(tokens);
entryAlertRepository.delete(entryAlert);
}

private void sendMessages(List<String> tokens) {
for (int i = 0; i < tokens.size(); i += BATCH_ALERT_SIZE) {
List<String> subTokens = tokens.subList(i, Math.min(i + BATCH_ALERT_SIZE, tokens.size()));
fcmClient.sendAllAsync(subTokens, FCMChannel.ENTRY_ALERT, FcmPayload.entryAlert());
}
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FCM이 한 번에 최대 500건까지 발송가능하더라구요?!
image

그래서 500건씩 보내줬는데, 이는 Async로 비동기로 진행했어요!

이게 X-lock 범위랑도 연관되어있어서, FCM 로직 전송시간동안 계속 connection을 점유한다면 connection 고갈문제로도 이어질 수 있어 Async로 진행하는게 옳다고 생각했어요!

이 때, 메세지 전송에 실패해도 entryAlertRepository.delete()가 호출된다는 점이 문젠데..
현재는 재시도 로직도 없고, 입장시간 지나서 재시도가 되어도 문제라고 생각했어요
그래서 fcm 메세지 실제 전송 성공 여부와 상관없이, EntryAlert는 제거해주는 방식을 택했습니다!!

Copy link
Collaborator

@seokjin8678 seokjin8678 Oct 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

해당 부분은 FCM에서의 제약 사항이니 sendMessages() 메서드의 for문이 fcmClient.sendAll()으로 옮겨야 될 것 같네요!

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

글렌 의견에 동의합니다.

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.festago.entry_alert.domain;

import com.festago.common.exception.BadRequestException;
import com.festago.common.exception.ErrorCode;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.validation.constraints.NotNull;
import java.time.LocalDateTime;

@Entity
public class EntryAlert {
xxeol2 marked this conversation as resolved.
Show resolved Hide resolved

private static final int ENTRY_ALERT_MINUTES_BEFORE = 10;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
private Long stageId;

@NotNull
private LocalDateTime entryTime;

protected EntryAlert() {
}

public EntryAlert(Long stageId, LocalDateTime entryTime) {
this(null, stageId, entryTime);
}

public EntryAlert(Long id, Long stageId, LocalDateTime entryTime) {
this.id = id;
this.stageId = stageId;
this.entryTime = entryTime;
}

public static EntryAlert create(Long stageId, LocalDateTime entryTime, LocalDateTime currentTime) {
if (currentTime.isAfter(entryTime.minusMinutes(ENTRY_ALERT_MINUTES_BEFORE))) {
throw new BadRequestException(ErrorCode.INVALID_ENTRY_ALERT_TIME);
}
return new EntryAlert(stageId, entryTime);
}

public LocalDateTime findAlertTime() {
return entryTime.minusMinutes(ENTRY_ALERT_MINUTES_BEFORE);
}

public Long getId() {
return id;
}

public Long getStageId() {
return stageId;
}

public LocalDateTime getEntryTime() {
return entryTime;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.festago.entry_alert.dto;

import java.time.LocalDateTime;

public record EntryAlertResponse(
Long id,
LocalDateTime alertTime
) {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.festago.entry_alert.repository;

import com.festago.entry_alert.domain.EntryAlert;
import jakarta.persistence.LockModeType;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface EntryAlertRepository extends JpaRepository<EntryAlert, Long> {

@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("SELECT ea FROM EntryAlert ea WHERE ea.id = :id")
Optional<EntryAlert> findByIdForUpdate(@Param("id") Long id);
}
Original file line number Diff line number Diff line change
@@ -1,90 +1,38 @@
package com.festago.fcm.application;

import com.festago.common.exception.ErrorCode;
import com.festago.common.exception.InternalServerException;
import com.festago.entry.dto.event.EntryProcessEvent;
import com.festago.fcm.domain.FCMChannel;
import com.festago.fcm.dto.FcmPayload;
import com.festago.fcm.dto.MemberFCMResponse;
import com.google.firebase.messaging.AndroidConfig;
import com.google.firebase.messaging.AndroidNotification;
import com.google.firebase.messaging.BatchResponse;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.FirebaseMessagingException;
import com.google.firebase.messaging.Message;
import com.google.firebase.messaging.SendResponse;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

@Component
@Profile({"dev", "prod"})
public class FCMNotificationEventListener {

private static final Logger log = LoggerFactory.getLogger(FCMNotificationEventListener.class);

private final FirebaseMessaging firebaseMessaging;
private final FcmClient fcmClient;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FcmClient 를 추상화해준 이유가 추후에 IosFcmClient, webFcmClient를 고려한 것이 맞을까용?

Copy link
Member Author

@xxeol2 xxeol2 Oct 5, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

확장을 위한 추상화보다는 DIP를 위한 추상화입니다!!
FirebaseMessaging은 외부 라이브러리라고 판단해 infrastructure 레이어에 두기 위해서 추상화를 진행했습니다..!

private final MemberFCMService memberFCMService;

public FCMNotificationEventListener(FirebaseMessaging firebaseMessaging, MemberFCMService memberFCMService) {
this.firebaseMessaging = firebaseMessaging;
public FCMNotificationEventListener(FcmClient fcmClient, MemberFCMService memberFCMService) {
this.fcmClient = fcmClient;
this.memberFCMService = memberFCMService;
}

@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
@Async
public void sendFcmNotification(EntryProcessEvent event) {
List<Message> messages = createMessages(getMemberFCMToken(event.memberId()), FCMChannel.NOT_DEFINED.name());
try {
BatchResponse batchResponse = firebaseMessaging.sendAll(messages);
checkAllSuccess(batchResponse, event.memberId());
} catch (FirebaseMessagingException e) {
log.error("fail send FCM message", e);
throw new InternalServerException(ErrorCode.FAIL_SEND_FCM_MESSAGE);
}
List<String> tokens = getMemberFCMToken(event.memberId());
fcmClient.sendAll(tokens, FCMChannel.ENTRY_PROCESS, FcmPayload.entryProcess());
}

private List<String> getMemberFCMToken(Long memberId) {
return memberFCMService.findMemberFCM(memberId).memberFCMs().stream()
return memberFCMService.findMemberFCM(memberId)
.memberFCMs()
.stream()
.map(MemberFCMResponse::fcmToken)
.toList();
}

private List<Message> createMessages(List<String> tokens, String channelId) {
return tokens.stream()
.map(token -> createMessage(token, channelId))
.toList();
}

private Message createMessage(String token, String channelId) {
return Message.builder()
.setAndroidConfig(createAndroidConfig(channelId))
.setToken(token)
.build();
}

private AndroidConfig createAndroidConfig(String channelId) {
return AndroidConfig.builder()
.setNotification(createAndroidNotification(channelId))
.build();
}

private AndroidNotification createAndroidNotification(String channelId) {
return AndroidNotification.builder()
.setChannelId(channelId)
.build();
}

private void checkAllSuccess(BatchResponse batchResponse, Long memberId) {
List<SendResponse> failSend = batchResponse.getResponses().stream()
.filter(sendResponse -> !sendResponse.isSuccessful())
.toList();

log.warn("member {} 에 대한 다음 요청들이 실패했습니다. {}", memberId, failSend);
throw new InternalServerException(ErrorCode.FAIL_SEND_FCM_MESSAGE);
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Component
public class FCMNotificationEventListener {

    private final FcmClient fcmClient;
    private final MemberFCMService memberFCMService;

    public FCMNotificationEventListener(FcmClient fcmClient, MemberFCMService memberFCMService) {
        this.fcmClient = fcmClient;
        this.memberFCMService = memberFCMService;
    }

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    @Async
    public void sendFcmNotification(EntryProcessEvent event) {
        List<String> tokens = memberFCMService.findAllMemberFCMToken(event.memberId());
        fcmClient.sendAll(tokens, FCMChannel.ENTRY_PROCESS, FcmPayload.entryProcess());
    }
}
@Service
@Transactional
public class MemberFCMService {
    ...
    @Transactional(readOnly = true)
    public List<String> findAllMemberFCMToken(Long memberId) {
        return memberFCMRepository.findAllTokenByMemberId(memberId);
    }
    ...
}
public interface MemberFCMRepository extends JpaRepository<MemberFCM, Long> {
    ...
    @Query("SELECT mf.fcmToken FROM MemberFCM mf WHERE mf.memberId = :memberId")
    List<String> findAllTokenByMemberId(@Param("memberId") Long memberId);
    ...
}

다음과 같은 방법은 어떠신가요?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

반영완료했습니다~

}
12 changes: 12 additions & 0 deletions backend/src/main/java/com/festago/fcm/application/FcmClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.festago.fcm.application;

import com.festago.fcm.domain.FCMChannel;
import com.festago.fcm.dto.FcmPayload;
import java.util.List;

public interface FcmClient {

void sendAllAsync(List<String> tokens, FCMChannel channel, FcmPayload fcmPayload);

void sendAll(List<String> tokens, FCMChannel channel, FcmPayload fcmPayload);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.festago.fcm.application;

import com.festago.fcm.domain.FCMChannel;
import com.festago.fcm.dto.FcmPayload;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
@Profile({"!prod", "!dev"})
xxeol2 marked this conversation as resolved.
Show resolved Hide resolved
public class MockFcmClient implements FcmClient {

private static final Logger log = LoggerFactory.getLogger(MockFcmClient.class);

@Override
@Async
public void sendAllAsync(List<String> tokens, FCMChannel channel, FcmPayload fcmPayload) {
sendAll(tokens, channel, fcmPayload);
}

@Override
public void sendAll(List<String> tokens, FCMChannel channel, FcmPayload fcmPayload) {
log.info("[FCM] title: {} / body: {} / to {} device", fcmPayload.title(), fcmPayload.body(), tokens.size());
}
}
Loading