整合Spring Cloud Stream Binder与GCP Pubsub进行消息发送与接收

1 前言

本文将简单介绍一下Spring Cloud StreamGoogle Cloud Pub/Sub的整合。

2 通过Emulator启动Pub/Sub

因使用实际的GCP Pub/Sub相对麻烦,本文通过模拟器来运行。

关于Google Cloud SDK的安装sql教程可参考: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

启动的时候设java基础教程置了项目名和端口。

3 整合

引入依赖:

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-gcp-pubsub-stream-binder</artifactId>
</dependency>

实现简单的python基础教程消息收发处理:

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属性c#教程与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

如果是vb.net教程实际的GCP Pub/Sub,指定key文件即可:

spring:
  cloud:
    gcp:
      credentials:
        location: file:/xxx.json

运行日志如下:

4 总结

代码请查看:https://github.com/LarryDpk/pkslow-samples

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值