如何使用 spring 引导在 Google Firebase FCM 上推送通知?

How to push notification on Google Firebase FCM using spring boot?

我正在寻找将通知从服务器(Spring Hibernate RESTful API)推送到客户端应用程序的解决方案,编码为 Angular 和 Android.我想实施一个不会占用太多用户带宽的解决方案,因为我的用户群的连接性有限(低带宽和 3G/2G 移动网络)。这排除了将轮询作为可能的解决方案。接下来,我研究了套接字连接,但看起来套接字连接可以保持打开状态并导致内存泄漏问题。接下来,我将尝试 Google FCM,但仍停留在实现过程中。具体来说,我试图在 FCM 上发送通知,但在客户端没有收到。 回顾一下,我必须从 JAVA 层(Spring 引导)发送通知,并在 angular 和 Android 上接收它。我尝试了一些示例代码来使用 FCM 完成这项工作。但它不起作用。请给我建议解决方案或不同的方法来完成这项工作。 这是我正在使用的代码:

    JSONObject body = new JSONObject();
            body.put("to", "/users/" + TOPIC);
            body.put("priority", "high");

            JSONObject notification = new JSONObject();
            notification.put("title", "JSA Notification");
            notification.put("body", "Happy Message!");

            JSONObject data = new JSONObject();
            data.put("Key-1", "JSA Data 1");
            data.put("Key-2", "JSA Data 2");

            body.put("notification", notification);
            body.put("data", data);

            HttpEntity<String> entity = new HttpEntity<>(body.toString());
            RestTemplate restTemplate = new RestTemplate();
            ArrayList<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
            interceptors.add(new HeaderRequestInterceptor("Authorization", "key=" + FIREBASE_SERVER_KEY));
            interceptors.add(new HeaderRequestInterceptor("Content-Type", "application/json"));
            restTemplate.setInterceptors(interceptors);
            String firebaseResponse = restTemplate.postForObject(FIREBASE_API_URL, entity, String.class);
            CompletableFuture<String> pushNotification = CompletableFuture.completedFuture(firebaseResponse);
            CompletableFuture.allOf(pushNotification).join();
        try {
            String firebaseResponse = pushNotification.get();
            System.out.println("reponse "+firebaseResponse);
            return new ResponseEntity<>(firebaseResponse, HttpStatus.OK);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

从 firebaseResponse,我在浏览器中得到以下响应:

{"multicast_id":6197426474050349577,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

我的消息好像没有发送出去。 非常感谢任何示例工作代码。 谢谢您的帮助。 - 普拉纳夫

FIREBASE_SERVER_KEY 是错误的。如果 FIREBASE_SERVER_KEY 是正确的,那么响应应该在下面。

{"multicast_id":7163645588662808791,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1563534037236589%eec6c0c0eec6c0c0"}]}

该问题有一个可接受的答案。但是对于那些在 2020 年阅读这篇文章的人来说,有一种更简单、更干净的方法可以使用 java.

的 firebase admin sdk 进行 firebase 推送通知。
        <dependency>
            <groupId>com.google.firebase</groupId>
            <artifactId>firebase-admin</artifactId>
            <version>7.0.0</version>
        </dependency>

将以上内容添加到您的项目后,您只需从 FCM admin console 生成一个 service-account.json 并发送如下通知。


    GoogleCredentials googleCredentials = GoogleCredentials
            .fromStream(new ClassPathResource("firebase-service-account.json").getInputStream());
    FirebaseOptions firebaseOptions = FirebaseOptions
            .builder()
            .setCredentials(googleCredentials)
            .build();
    FirebaseApp app = FirebaseApp.initializeApp(firebaseOptions, "my-app");
    FirebaseMessaging firebaseMessaging = FirebaseMessaging.getInstance(app);
        Notification notification = Notification
                .builder()
                .setTitle(note.getSubject())
                .setBody(note.getContent())
                .build();

        Message message = Message
                .builder()
                .setToken(token)            //this can be setTopic() too
                .setNotification(notification)
                .putAllData(note.getData())
                .build();

        return firebaseMessaging.send(message);

我有一个详细的post关于如何在spring引导项目中实现它。

https://springhow.com/spring-boot-firebase-push-notification/