-
Notifications
You must be signed in to change notification settings - Fork 5
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
refactor: fcm 서버 비동기 처리 구현 #499
Merged
The head ref may contain hidden characters: "refactor/498-FCM_\uC11C\uBC84_\uBE44\uB3D9\uAE30\uCC98\uB9AC_\uAD6C\uD604"
Merged
Changes from 9 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
69dbe3a
refactor: fcm sdk 적용 및 fcm 서버측 알림처리 비동기 설정
rawfishthelgh b92cfc6
refactor: FCM 초기화 로직 변경
Kim0914 53ba512
refactor: FCM 파일 경로 변경
Kim0914 085478e
refactor: FCM 인스턴스 명 변경
Kim0914 df6960a
test: 알림 테스트 계정 변경
rawfishthelgh ec1c882
chore: Async 스레드 풀 개수 변경
Kim0914 53c10f7
Merge remote-tracking branch 'origin/refactor/498-FCM_서버_비동기처리_구현' in…
Kim0914 397222e
chore: 알림 로깅 추가 및 불필요한 코드 삭제
Kim0914 370e931
refactor: 파일 경로 정적 변수로 추출
Kim0914 0830d12
refactor: 비동기 스레드 풀 40으로 설정
Kim0914 c899096
chore: 현재 필요하지 않는 테스트 메서드 주석 처리
Kim0914 2df1dd3
chore: FCM 정적 변수 빈 주입으로 변경
Kim0914 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
99 changes: 40 additions & 59 deletions
99
...d/pium/src/main/java/com/official/pium/notification/fcm/application/FcmMessageSender.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,81 +1,62 @@ | ||
package com.official.pium.notification.fcm.application; | ||
|
||
import com.google.auth.oauth2.GoogleCredentials; | ||
import com.official.pium.notification.fcm.dto.FcmMessageResponse; | ||
import com.official.pium.notification.fcm.exception.FcmException; | ||
import com.google.firebase.FirebaseApp; | ||
import com.google.firebase.FirebaseOptions; | ||
import com.google.firebase.messaging.FirebaseMessaging; | ||
import com.google.firebase.messaging.Message; | ||
import com.google.firebase.messaging.Notification; | ||
import com.official.pium.notification.application.MessageSendManager; | ||
import jakarta.annotation.PostConstruct; | ||
import java.io.FileNotFoundException; | ||
import java.io.IOException; | ||
import java.util.concurrent.ExecutionException; | ||
import lombok.RequiredArgsConstructor; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.core.io.ClassPathResource; | ||
import org.springframework.http.HttpEntity; | ||
import org.springframework.http.HttpHeaders; | ||
import org.springframework.http.ResponseEntity; | ||
import org.springframework.stereotype.Component; | ||
import org.springframework.web.client.RestTemplate; | ||
import java.io.IOException; | ||
|
||
@Slf4j | ||
@Component | ||
@RequiredArgsConstructor | ||
public class FcmMessageSender implements MessageSendManager { | ||
|
||
@Value("${fcm.api.url}") | ||
private String apiUrl; | ||
|
||
@Value("${fcm.key.path}") | ||
private String keyPath; | ||
|
||
@Value("${fcm.key.scope}") | ||
private String keyScope; | ||
|
||
private final RestTemplate restTemplate; | ||
private static final String FCM_JSON_PATH = "config/pium-fcm.json"; | ||
|
||
public void sendMessageTo(String targetToken, String title, String body) { | ||
@PostConstruct | ||
public void initialize() { | ||
try { | ||
FcmMessageResponse message = makeMessage(targetToken, title, body); | ||
|
||
HttpHeaders headers = new HttpHeaders(); | ||
headers.set(HttpHeaders.AUTHORIZATION, "Bearer " + getAccessToken()); | ||
headers.set(HttpHeaders.CONTENT_TYPE, "application/json; UTF-8"); | ||
|
||
HttpEntity<FcmMessageResponse> request = new HttpEntity<>(message, headers); | ||
|
||
ResponseEntity<FcmMessageResponse> postResult = restTemplate.postForEntity( | ||
apiUrl, | ||
request, | ||
FcmMessageResponse.class | ||
); | ||
|
||
log.info("FCM 메시지 전송 성공: {}", postResult.getBody()); | ||
|
||
} catch (Exception e) { | ||
log.error("FCM 메시지 전송 실패", e); | ||
throw new FcmException.FcmMessageSendException(e.getMessage()); | ||
ClassPathResource resource = new ClassPathResource(FCM_JSON_PATH); | ||
FirebaseOptions options = FirebaseOptions.builder() | ||
.setCredentials(GoogleCredentials.fromStream(resource.getInputStream())) | ||
.build(); | ||
|
||
if (FirebaseApp.getApps().isEmpty()) { | ||
FirebaseApp.initializeApp(options); | ||
} | ||
} catch (FileNotFoundException e) { | ||
log.error("파일을 찾을 수 없습니다. ", e); | ||
} catch (IOException e) { | ||
log.error("FCM 인증이 실패했습니다. ", e); | ||
} | ||
} | ||
|
||
private FcmMessageResponse makeMessage(String targetToken, String title, String body) { | ||
return FcmMessageResponse.builder() | ||
.message(FcmMessageResponse.Message.builder() | ||
.token(targetToken) | ||
.notification(FcmMessageResponse.Notification.builder() | ||
.title(title) | ||
.body(body) | ||
.image(null) | ||
.build() | ||
) | ||
.build() | ||
) | ||
.validate_only(false) | ||
public void sendMessageTo(String targetToken, String title, String body) { | ||
Notification notification = Notification.builder() | ||
.setTitle(title) | ||
.setBody(body) | ||
.build(); | ||
} | ||
|
||
private String getAccessToken() throws IOException { | ||
GoogleCredentials googleCredentials = GoogleCredentials | ||
.fromStream(new ClassPathResource(keyPath).getInputStream()) | ||
.createScoped(keyScope); | ||
googleCredentials.refreshIfExpired(); | ||
return googleCredentials.getAccessToken().getTokenValue(); | ||
Message message = Message.builder() | ||
.setToken(targetToken) | ||
.setNotification(notification) | ||
.build(); | ||
try { | ||
String response = FirebaseMessaging.getInstance().sendAsync(message).get(); | ||
log.info("알림 전송 성공 : " + response); | ||
} catch (InterruptedException e) { | ||
log.error("FCM 알림 스레드에서 문제가 발생했습니다.", e); | ||
} catch (ExecutionException e) { | ||
log.error("FCM 알림 전송에 실패했습니다.", e); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A
Value가 아니라 상수로 선언해서 약간 의아했는데
@PostConstruct
때문에 이렇게 한걸까요?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ㅋㅋㅋ PR 올리고 할까 말까 고민중이었는데 제 마음을 잘 캐치해주셨네요
반영완류