整合Spring Cloud Stream Binder與GCP Pubsub進行消息發送與接收

我最新最全的文章都在 南瓜慢說 www.pkslow.com ,歡迎大家來喝茶!

1 前言

之前的文章《整合Spring Cloud Stream Binder與RabbitMQ進行消息發送與接收》講解了Spring Cloud streamRabbitMQ的整合,本文將簡單介紹一下Spring Cloud StreamGoogle 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/pkslow-samples


歡迎關注微信公衆號<南瓜慢說>,將持續爲你更新...

多讀書,多分享;多寫作,多整理。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章