팀프로젝트 과정에서 좋아요가 눌렸을 경우 알림이 오도록 하기 위해서 firebase를 사용해야했다.
NotificationService.java
@Component
@RequiredArgsConstructor
public class NotificationService {
private final String API_URL = "";
private final ObjectMapper objectMapper;
public void sendMessageTo(String targetToken, String title, String body) throws IOException {
String message = makeMessage(targetToken, title, body);
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = RequestBody.create(message,
MediaType.get("application/json; charset=utf-8"));
Request request = new Request.Builder()
.url(API_URL)
.post(requestBody)
.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + getAccessToken())
.addHeader(HttpHeaders.CONTENT_TYPE, "application/json; UTF-8")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
}
private String makeMessage(String targetToken, String title, String body) throws JsonParseException, JsonProcessingException {
NotificationMessage notificationMessage = NotificationMessage.builder()
.message(NotificationMessage.Message.builder()
.token(targetToken)
.notification(NotificationMessage.Notification.builder()
.title(title)
.body(body)
.image(null)
.build()
).build()).validateOnly(false).build();
return objectMapper.writeValueAsString(notificationMessage);
}
private String getAccessToken() throws IOException {
String firebaseConfigPath = "firebase_service_key.json";
GoogleCredentials googleCredentials = GoogleCredentials
.fromStream(new ClassPathResource(firebaseConfigPath).getInputStream())
.createScoped(List.of(""));
googleCredentials.refreshIfExpired();
return googleCredentials.getAccessToken().getTokenValue();
}
@Scheduled(fixedRate = 60000) // 예: 1분마다 실행
public void sendPeriodicNotifications() {
// 알림을 보내는 로직
}
public void sendLikeNotification(Long postId) {
}
public void sendTopPostNotification(Long postId) {
}
}
NotificationMessage.java
@Builder
@AllArgsConstructor
@Getter
public class NotificationMessage {
private boolean validateOnly;
private Message message;
@Builder
@AllArgsConstructor
@Getter
public static class Message {
private Notification notification;
private String token;
}
@Builder
@AllArgsConstructor
@Getter
public static class Notification {
private String title;
private String body;
private String image;
}
}
NotificationRequest.java
@Getter
@Setter
public class NotificationRequest {
private String targetToken;
private String title;
private String body;
}