我最新最全的文章都在 南瓜慢说 www.pkslow.com,欢送大家来喝茶!
1 前言
之前的文章《整合 Spring Cloud Stream Binder 与 RabbitMQ 进行音讯发送与接管》解说了 Spring Cloud stream
与RabbitMQ
的整合,本文将简略介绍一下 Spring Cloud Stream
与Google Cloud Pub/Sub
的整合。
2 通过 Emulator 启动 Pub/Sub
因应用理论的 GCP Pub/Sub 绝对麻烦,本文通过模拟器来运行。
对于 Google Cloud SDK
的装置可参考:Mac 装置 Google Cloud SDK
装置必要的组件:
gcloud components install beta
gcloud components install pubsub-emulator
启动模拟器:
$ 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
启动的时候设置了我的项目名和端口。
3 整合
引入依赖:
<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 属性:
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 文件即可:
spring:
cloud:
gcp:
credentials:
location: file:/xxx.json
运行日志如下:
4 总结
代码请查看:https://github.com/LarryDpk/p…
欢送关注微信公众号 <南瓜慢说>,将继续为你更新 …
多读书,多分享;多写作,多整顿。