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

refactor: fcm 서버 비동기 처리 구현 #499

Merged
merged 12 commits into from
Jan 25, 2024
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public class TestService {
// }

public void sendWaterNotificationAsyncRampTest() {
List<PetPlant> petPlants = petPlantRepository.findAllByMemberId(6L);
List<PetPlant> petPlants = petPlantRepository.findAllByMemberId(7L);
// List<NotificationEvent> events = petPlants.stream()
// .map(plant -> NotificationEvent.builder()
// .title(plant.getNickname())
Expand All @@ -61,7 +61,7 @@ public void sendWaterNotificationAsyncRampTest() {
}

public void sendWaterNotificationAsyncTest() {
List<PetPlant> petPlants = petPlantRepository.findAllByMemberId(6L);
List<PetPlant> petPlants = petPlantRepository.findAllByMemberId(7L);
List<NotificationEvent> events = petPlants.stream()
.map(plant -> NotificationEvent.builder()
.title(plant.getNickname())
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package com.official.pium.admin.ui;

import com.official.pium.admin.service.TestService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

Expand All @@ -9,23 +12,17 @@
@RequestMapping("/test")
public class TestController {

// private final TestService testService;
private final TestService testService;

// @GetMapping("/notifications")
// public ResponseEntity<String> notificationTest() {
// testService.sendWaterNotificationTest();
// return ResponseEntity.ok("알림 기능 테스트 성공");
// }
@GetMapping("/notifications/ramp")
public ResponseEntity<String> notificationRampTest() {
testService.sendWaterNotificationAsyncRampTest();
return ResponseEntity.ok("비동기 알림 기능 테스트 램프업 성공");
}

// @GetMapping("/notifications/ramp")
// public ResponseEntity<String> notificationRampTest() {
// testService.sendWaterNotificationAsyncRampTest();
// return ResponseEntity.ok("비동기 알림 기능 테스트 램프업 성공");
// }
//
// @GetMapping("/notifications/async")
// public ResponseEntity<String> notificationAsyncTest() {
// testService.sendWaterNotificationAsyncTest();
// return ResponseEntity.ok("비동기 알림 기능 테스트 성공");
// }
@GetMapping("/notifications/async")
public ResponseEntity<String> notificationAsyncTest() {
testService.sendWaterNotificationAsyncTest();
return ResponseEntity.ok("비동기 알림 기능 테스트 성공");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(40);
executor.setCorePoolSize(20);
executor.setThreadNamePrefix("2024-Pium-Thread: ");
executor.initialize();
return executor;
Expand Down
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";
Copy link
Collaborator

Choose a reason for hiding this comment

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

A

Value가 아니라 상수로 선언해서 약간 의아했는데 @PostConstruct 때문에 이렇게 한걸까요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

ㅋㅋㅋ PR 올리고 할까 말까 고민중이었는데 제 마음을 잘 캐치해주셨네요
반영완류


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);
}
}
}
Loading