-->

스프링

 

(1) 어떤 플랫폼에서 푸시를 보낼 것인가?


푸시 알림은 모바일 앱, 웹, 데스크톱 알림 등 여러 방식이 있는데, 보통은 Firebase Cloud Messaging(FCM) 을 많이 사용합니다.

  • 모바일 앱 (Android, iOS) → FCM 사용

 

  • 웹 푸시 알림 → FCM + Web Push API 사용

 

  • 데스크톱 → OS별 알림 시스템 연동

결론: 모바일 앱이라면 FCM, 웹이라면 FCM + Web Push API 가 적절함.

 

1.FCM을 활용한 푸시 알림 구현 (Spring Boot + MySQL + Firebase Cloud Messaging)

 1. Firebase 프로젝트 설정

  1. Firebase Console에서 프로젝트 생성
  2. Cloud Messaging 활성화
  3. google-services.json 파일 다운로드 (Android) / firebase-adminsdk.json 다운로드 (백엔드)
  4. 서버 키(Server Key) 복사 (FCM API 호출에 필요)

 

 

 

 2. Spring Boot에서 FCM 연동 (푸시 알림 전송)

1)필요한 의존성 추가 (pom.xml)

<dependency>
    <groupId>com.google.firebase</groupId>
    <artifactId>firebase-admin</artifactId>
    <version>9.2.0</version>
</dependency>

 

 

2)Firebase 초기화 설정 (FirebaseConfig.java)

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import jakarta.annotation.PostConstruct;
import org.springframework.context.annotation.Configuration;

import java.io.FileInputStream;
import java.io.IOException;

@Configuration
public class FirebaseConfig {

    @PostConstruct
    public void initializeFirebase() throws IOException {
        FileInputStream serviceAccount =
                new FileInputStream("src/main/resources/firebase-adminsdk.json");

        FirebaseOptions options = FirebaseOptions.builder()
                .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                .build();

        if (FirebaseApp.getApps().isEmpty()) {
            FirebaseApp.initializeApp(options);
        }
    }
}

firebase-adminsdk.json 파일 경로를 프로젝트 내부에 두고 초기화.

 

 

3)푸시 알림 전송 서비스 (FcmService.java)

import com.google.firebase.messaging.*;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutionException;

@Service
public class FcmService {

    public String sendNotification(String token, String title, String body) throws ExecutionException, InterruptedException {
        Notification notification = Notification.builder()
                .setTitle(title)
                .setBody(body)
                .build();

        Message message = Message.builder()
                .setToken(token)
                .setNotification(notification)
                .build();

        return FirebaseMessaging.getInstance().sendAsync(message).get();
    }
}

  FCM 토큰을 가진 특정 사용자에게 푸시 알림을 보냄


???? token 값은 클라이언트(Android/iOS)에서 FCM을 통해 받은 디바이스 토큰

 

 

4)푸시 알림 전송 API (FcmController.java)

import org.springframework.web.bind.annotation.*;

import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/api/notifications")
public class FcmController {

    private final FcmService fcmService;

    public FcmController(FcmService fcmService) {
        this.fcmService = fcmService;
    }

    @PostMapping("/send")
    public String sendNotification(@RequestParam String token,
                                   @RequestParam String title,
                                   @RequestParam String body) throws ExecutionException, InterruptedException {
        return fcmService.sendNotification(token, title, body);
    }
}

이제 /api/notifications/send API를 호출하면 푸시 알림 전송 가능

 

 

 

 

 

2.  MySQL + 이벤트 기반으로 자동 푸시 전송

 

MySQL 데이터 변경을 감지하여 자동으로 푸시 알림을 보내려면 Spring Boot의 이벤트 리스너 또는 데이터베이스 트리거를 사용할 수 있습니다.

1) 방법 1: JPA 이벤트 리스너 사용

import jakarta.persistence.*;

@Entity
@EntityListeners(NotificationEntityListener.class)
public class Notification {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    private String message;
    private String userToken; // FCM 토큰

    // Getter & Setter
}

 

import jakarta.persistence.PostPersist;
import java.util.concurrent.ExecutionException;

public class NotificationEntityListener {

    @PostPersist
    public void onPostPersist(Notification notification) {
        FcmService fcmService = new FcmService(); // Service 주입 필요
        try {
            fcmService.sendNotification(notification.getUserToken(), "새로운 알림", notification.getMessage());
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

새로운 알림 데이터가 추가되면 자동으로 푸시 알림 전송!

 

 

 

 

2)방법 2: MySQL 트리거 + Spring Boot 이벤트 핸들링

1.MySQL 트리거 생성

CREATE TRIGGER send_push_after_insert
AFTER INSERT ON notifications
FOR EACH ROW
INSERT INTO push_queue (user_token, message) VALUES (NEW.user_token, NEW.message);

 

2.Spring Boot에서 push_queue 테이블을 주기적으로 체크 & 푸시 전송

@Scheduled(fixedRate = 5000)
public void sendQueuedNotifications() {
    List<PushQueue> pushQueueList = pushQueueRepository.findAll();
    
    for (PushQueue push : pushQueueList) {
        fcmService.sendNotification(push.getUserToken(), "새로운 알림", push.getMessage());
        pushQueueRepository.delete(push); // 처리된 알림 삭제
    }
}

MySQL에서 새로운 알림이 들어오면 푸시 큐(push_queue) 테이블에 저장
???? Spring Boot가 주기적으로 확인 후 푸시 전송

 

 

결론: Spring Boot + MySQL 푸시 알림 구현

Firebase Cloud Messaging(FCM) API 사용 → 모바일 푸시 알림 가능
JPA 이벤트 리스너 or MySQL 트리거 활용 → 데이터 변경 감지 후 자동 푸시 전송
웹 푸시 알림은 Web Push API + FCM 조합으로 구현 가능
x Firebase보다 기본 제공 기능이 없어서 직접 구현해야 하지만, 확장성이 좋음

 

 

 어렵냐?

단순한 API 호출 방식(FcmController) → 쉽다
JPA 이벤트 리스너 활용 → 중간 난이도
MySQL 트리거 + Spring Scheduler → 조금 복잡하지만 자동화 가능

즉, 한번 설정하면 자동으로 푸시가 나가도록 만들 수 있어서 편하지만, 초기 설정은 약간 귀찮다.
하지만 백엔드에서 커스텀 알림 로직을 자유롭게 만들 수 있어서 확장성이 좋음! 

 

 

FCM 무료 사용 범위

  • 푸시 알림 전송: 무제한 무료
  • 디바이스 토큰 등록 및 관리: 무료
  • 토픽 메시징(Topic Messaging): 무료
  • 구독 기반 알림(Group Messaging): 무료

즉, 푸시 알림을 보내는 것 자체에는 비용이 들지 않습니다.

 

 

그런데 주의할 점!

FCM 자체는 무료지만, 다른 Firebase 기능과 함께 사용할 경우 비용이 발생할 수 있음

  1. Firebase Realtime Database / Firestore → 무료 용량 초과 시 과금
  2. Cloud Functions (서버리스 함수) → 일정량 이상 사용하면 비용 발생
  3. BigQuery 연동 → 사용량에 따라 비용 발생

하지만, 푸시 알림(Firebase Cloud Messaging)만 사용한다면 완전 무료!

 

 

 

 

3.  FCM 사용을 위한    설정 

가입 후 바로 사용하려면 Firebase 프로젝트를 생성하고, FCM 설정을 해야 합니다.
순서는 다음과 같습니다.

 

1️⃣ Firebase 가입 및 프로젝트 생성

  1. Firebase Console에 접속
  2. Google 계정으로 로그인
  3. 새 프로젝트 생성 (+ 프로젝트 추가)
  4. 프로젝트 이름 입력 후 생성 완료

 

 

2️⃣ FCM 설정 (푸시 알림 활성화)

웹(Web) / Android / iOS 플랫폼에 따라 설정 필요

 (A) 웹(Web) FCM 설정

  • 프로젝트 설정 > 클라우드 메시징으로 이동
  • 서버 키(Server Key) 확인 (API 호출에 필요)
  • Web Push 사용 시 VAPID Key 생성
  • Firebase SDK를 프론트엔드에 추가하여 사용

 (B) Android FCM 설정

  • 프로젝트 설정 > 일반에서 google-services.json 다운로드
  • Android 앱의 app 폴더에 추가
  • Firebase SDK 추가 (build.gradle 수정)
  • 앱에서 FCM 초기화 후 디바이스 토큰 받기

 (C) iOS FCM 설정

  • GoogleService-Info.plist 다운로드 후 Xcode 프로젝트에 추가
  • APNs 인증서(푸시 인증서) 업로드
  • Firebase SDK 추가 후 앱에서 FCM 등록

 

 

 

3️⃣ 푸시 알림 테스트 (Postman or API 호출)

FCM 설정이 완료되면, Postman이나 Spring Boot API 를 통해 푸시 알림을 전송할 수 있습니다.

Postman 예제 (FCM 서버 키 사용)

 

POST https://fcm.googleapis.com/fcm/send
Headers:
- Authorization: key=YOUR_SERVER_KEY
- Content-Type: application/json

Body:
{
  "to": "DEVICE_TOKEN",
  "notification": {
    "title": "테스트 알림",
    "body": "FCM 설정이 완료되었습니다!"
  }
}

 

DEVICE_TOKEN은 클라이언트(Android/iOS)에서 받은 FCM 토큰

 

 

가입 후 간단한 설정만 하면 바로 사용 가능!

Firebase 가입 후 프로젝트 만들면 기본적으로 무료 사용 가능
FCM을 사용하려면 서버 키(Server Key) 확인 & SDK 설정 필요
웹 / Android / iOS에 맞춰 Firebase 설정이 필요하지만, 어렵지 않음
Postman으로 FCM API를 호출하면 바로 푸시 알림 테스트 가능! 

===> 가입 후 10~20분 정도 설정하면 바로 푸시 알림을 보낼 수 있음!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

about author

PHRASE

Level 1  라이트

댓글 ( 1)

댓글 남기기

작성