visualkhh
4k
2021-02-04 10:59:41 작성 2021-02-04 11:06:34 수정됨
2
565

spring에서 fcm (firebase cloud messaging) push 보내기.


spring에서 fcm (firebase cloud messaging) push 보내기.

공식문서: https://firebase.google.com/docs/cloud-messaging/server?hl=ko

설정방법

- firebase 에서 키생성 파일다운로드 ...key.json 받기.

  다른방법도있다 위공식문서 참고.


build.gradle

compile group: 'com.google.firebase', name: 'firebase-admin', version: '7.1.0'


service


@Service
@Slf4j
public class FcmService {


@Value("${project.properties.firebase-create-scoped}")
String fireBaseCreateScoped;
private FirebaseMessaging instance;

public void sendTargetMessage(String targetToken, String title, String body) throws FirebaseMessagingException {
this.sendTargetMessage(targetToken, title, body, null);
}
public void sendTargetMessage(String targetToken, String title, String body, String image) throws FirebaseMessagingException {
Notification notification = Notification.builder().setTitle(title).setBody(body).setImage(image).build();
Message msg = Message.builder().setToken(targetToken).setNotification(notification).build();
sendMessage(msg);
}

public void sendTopicMessage(String topic, String title, String body) throws FirebaseMessagingException {
this.sendTopicMessage(topic, title, body, null);
}
public void sendTopicMessage(String topic, String title, String body, String image) throws FirebaseMessagingException {
Notification notification = Notification.builder().setTitle(title).setBody(body).setImage(image).build();
Message msg = Message.builder().setTopic(topic).setNotification(notification).build();
sendMessage(msg);
}

public String sendMessage(Message message) throws FirebaseMessagingException {
return this.instance.send(message);
}

@PostConstruct
public void firebaseSetting() throws IOException {
GoogleCredentials googleCredentials = GoogleCredentials.fromStream(new ClassPathResource("google-fcm-...-key.json").getInputStream())
.createScoped((Arrays.asList(fireBaseCreateScoped)));

FirebaseOptions secondaryAppConfig = FirebaseOptions.builder()
.setCredentials(googleCredentials)
.build();
FirebaseApp app = FirebaseApp.initializeApp(secondaryAppConfig);
this.instance = FirebaseMessaging.getInstance(app);
}

public BatchResponse sendMessage(MulticastMessage message) throws FirebaseMessagingException {
return this.instance.sendMulticast(message);
}
}


application.yaml

project:
properties:
firebase-create-scoped: "https://www.googleapis.com/auth/firebase.messaging"
firebase-multicast-message-size: 500



controller

@Slf4j
@RestController
@RequestMapping(NotificationsController.URI_PREFIX)
@Api(tags = "알림")
public class NotificationsController {
public static final String URI_PREFIX = ApisController.URI_PREFIX + "/notifications";

@Autowired
FcmService fcmService;

@Autowired
CoreUserService coreUserService;


@Value("${project.properties.firebase-multicast-message-size}")
Long multicastMessageSize;


@ApiOperation(value = "토픽푸쉬")
@PostMapping(value = "/pushs/topics/{topic}")
public void notificationTopics(@PathVariable("topic") String topic, @RequestBody RequestPushMessage data) throws FirebaseMessagingException {
Notification notification = Notification.builder().setTitle(data.getTitle()).setBody(data.getBody()).setImage(data.getImage()).build();
Message.Builder builder = Message.builder();
Optional.ofNullable(data.getData()).ifPresent(sit -> builder.putAllData(sit));
Message msg = builder.setTopic(topic).setNotification(notification).build();
fcmService.sendMessage(msg);
}

@ApiOperation(value = "전고객푸쉬")
@PostMapping(value = "/pushs/users")
public void notificationUsers(@RequestBody RequestPushMessage data) throws IOException, FirebaseMessagingException {
List<CoreUser> targetUser = null == data.getUserNos() ? coreUserService.findAllByEnabledAndPushTokenIsNotNull(UseCd.USE001) : coreUserService.findAllByEnabledAndPushTokenIsNotNullAndNoIn(UseCd.USE001, data.getUserNos());
AtomicInteger counter = new AtomicInteger();
Collection<List<CoreUser>> sendUserGroups = targetUser.stream().collect(Collectors.groupingBy(it -> counter.getAndIncrement() / multicastMessageSize.longValue())).values();
for (List<CoreUser> it : sendUserGroups) {
Notification notification = Notification.builder().setTitle(data.getTitle()).setBody(data.getBody()).setImage(data.getImage()).build();
MulticastMessage.Builder builder = MulticastMessage.builder();
Optional.ofNullable(data.getData()).ifPresent(sit -> builder.putAllData(sit));
MulticastMessage message = builder
.setNotification(notification)
.addAllTokens(it.stream().map(sit -> sit.getPushToken()).collect(Collectors.toList()))
.build();
this.fcmService.sendMessage(message);
}
}


@ApiOperation(value = "특정 고객푸쉬")
@PostMapping(value = "/pushs/users/{no}")
public void notificationUser(@PathVariable("no") Long no, @RequestBody RequestPushMessage data) throws FirebaseMessagingException {
Optional<CoreUser> user = coreUserService.findById(no);
if (user.isPresent()) {
CoreUser it = user.get();
Notification notification = Notification.builder().setTitle(data.getTitle()).setBody(data.getBody()).setImage(data.getImage()).build();
Message.Builder builder = Message.builder();
Optional.ofNullable(data.getData()).ifPresent(sit -> builder.putAllData(sit));
Message msg = builder.setToken(it.getPushToken()).setNotification(notification).build();
fcmService.sendMessage(msg);
}
}



}


어플테스트

- android app

https://github.com/firebase/quickstart-android/tree/master/messaging




감사합니다.

0
  • 댓글 2

  • 저놈자바가
    1k
    2021-02-04 11:04:07

    좋은 정보 감사합니다

    전고객푸쉬가 두개있는건 오타인거죠?

  • visualkhh
    4k
    2021-02-04 11:06:48

    @재미없다~ 

    그렇네요 ㅎㅎ 수정했습니다. 감사합니다.

  • 로그인을 하시면 댓글을 등록할 수 있습니다.