IT/spring
spring에서 FCM (firebase cloud messaging) push 보내기.
삶의여행자
2021. 2. 4. 11:01
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
감사합니다.