我最新最全的文章都在 南瓜慢說 www.pkslow.com ,歡迎你們來喝茶!
以前的文章《整合Spring Cloud Stream Binder與RabbitMQ進行消息發送與接收》講解了Spring Cloud stream
與RabbitMQ
的整合,本文將簡單介紹一下Spring Cloud Stream
與Google Cloud Pub/Sub
的整合。html
因使用實際的GCP Pub/Sub相對麻煩,本文經過模擬器來運行。java
關於Google Cloud SDK
的安裝可參考:Mac安裝Google Cloud SDKgit
安裝必要的組件:github
gcloud components install beta gcloud components install pubsub-emulator
啓動模擬器:spring
$ gcloud beta emulators pubsub start --project=pkslow-prj --host-port=0.0.0.0:8511 Executing: /google-cloud-sdk/platform/pubsub-emulator/bin/cloud-pubsub-emulator --host=0.0.0.0 --port=8511 [pubsub] This is the Google Pub/Sub fake. [pubsub] Implementation may be incomplete or differ from the real system. [pubsub] May 11, 2021 10:27:31 PM com.google.cloud.pubsub.testing.v1.Main main [pubsub] INFO: IAM integration is disabled. IAM policy methods and ACL checks are not supported [pubsub] SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". [pubsub] SLF4J: Defaulting to no-operation (NOP) logger implementation [pubsub] SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. [pubsub] May 11, 2021 10:27:32 PM com.google.cloud.pubsub.testing.v1.Main main [pubsub] INFO: Server started, listening on 8511
啓動的時候設置了項目名和端口。json
引入依賴:bash
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-gcp-pubsub-stream-binder</artifactId> </dependency>
實現簡單的消息收發處理:微信
package com.pkslow.cloud.stream.binder.pubsub; @SpringBootApplication public class StreamBinderPubsub { private static final Logger log = LoggerFactory.getLogger(StreamBinderPubsub.class); public static void main(String[] args) { SpringApplication.run(StreamBinderPubsub.class, args); } @Bean public Supplier<String> pkslowSource() { return () -> { String message = "www.pkslow.com"; log.info("Sending value: " + message); return message; }; } @Bean public Consumer<String> pkslowSink() { return message -> { log.info("Received message " + message); }; } }
配置Pub/Sub屬性與Cloud Stream屬性:google
spring: cloud: stream: function: definition: pkslowSource;pkslowSink bindings: pkslowSource-out-0: destination: pkslow-topic pkslowSink-in-0: destination: pkslow-topic poller: fixed-delay: 500 gcp: pubsub: emulator-host: localhost:8511 project-id: pkslow-prj
若是是實際的GCP Pub/Sub
,指定key文件便可:spa
spring: cloud: gcp: credentials: location: file:/xxx.json
運行日誌以下:
代碼請查看:https://github.com/LarryDpk/p...
歡迎關注微信公衆號<南瓜慢說>,將持續爲你更新...
多讀書,多分享;多寫做,多整理。