使用Spring Boot在Google Firebase FCM上推送通知的步骤如下:
pom.xml
文件中添加以下依赖:<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>8.0.0</version>
</dependency>
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.io.FileInputStream;
import java.io.IOException;
@Configuration
public class FirebaseConfig {
@PostConstruct
public void initialize() throws IOException {
FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountKey.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.build();
FirebaseApp.initializeApp(options);
}
}
请确保将path/to/serviceAccountKey.json
替换为您的Firebase服务账号密钥文件的路径。
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.Message;
import com.google.firebase.messaging.Notification;
import org.springframework.stereotype.Service;
@Service
public class NotificationService {
public void sendNotification(String title, String body, String token) {
Message message = Message.builder()
.setNotification(new Notification(title, body))
.setToken(token)
.build();
try {
FirebaseMessaging.getInstance().send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class NotificationController {
@Autowired
private NotificationService notificationService;
@PostMapping("/send-notification")
public void sendNotification(@RequestBody NotificationRequest request) {
notificationService.sendNotification(request.getTitle(), request.getBody(), request.getToken());
}
}
请根据实际需求自定义NotificationRequest类,用于接收发送通知的请求参数。
以上是使用Spring Boot在Google Firebase FCM上推送通知的基本步骤。通过Firebase Admin SDK和FirebaseMessaging类,我们可以方便地在Spring Boot应用程序中实现与FCM的通信。
领取专属 10元无门槛券
手把手带您无忧上云