【问题标题】:How to publish a Pub/Sub message with a Supplier bean?如何使用供应商 bean 发布 Pub/Sub 消息?
【发布时间】:2022-06-16 14:42:50
【问题描述】:

我想根据 Google 文档在 Spring 中发布 Pub/Sub 消息(请参阅 https://cloud.google.com/pubsub/docs/spring#publishing-messages-using-stream-binder)。唯一的问题是我是 Spring Framework 的新手,我不知道如何将这个示例变成我可以使用的东西。也就是说,一种允许我将特定消息从服务发送到 Pub/Sub 主题的方法。

// Create an output binder to send messages to `topic-one` using a Supplier bean.
@Bean
public Supplier<Flux<Message<String>>> sendMessageToTopicOne() {
  return () ->
      Flux.<Message<String>>generate(
              sink -> {
                try {
                  Thread.sleep(10000);
                } catch (InterruptedException e) {
                  // Stop sleep earlier.
                }

                Message<String> message =
                    MessageBuilder.withPayload("message-" + rand.nextInt(1000)).build();
                LOGGER.info(
                    "Sending a message via the output binder to topic-one! Payload: "
                        + message.getPayload());
                sink.next(message);
              })
          .subscribeOn(Schedulers.boundedElastic());
}

如何编写一个方法,让我可以向我的 Pub/Sub 主题发送特定消息(比如说“字符串”),该主题可以从服务中调用?

【问题讨论】:

  • 使用 Java 库,而不是 spring 集成。
  • @guillaumeblaquiere 我对 Google 文章中的第一种方法(没有 Spring 集成)有一些问题。我的目标是通过 Pub/Sub 发送对象。但是,我没有设法将它序列化而没有错误,而 Spring 的集成可以为我处理。这就是为什么我打算将它与 Message 和 MessageBuilder 类一起使用。
  • 嗨@FOR_SCIENCE,根据您的要求,您可以尝试documentation中给出的步骤。如果有帮助,请告诉我。

标签: java spring google-cloud-pubsub


【解决方案1】:

我现在在 Channels 中使用一种旧的且已弃用的方法,但到目前为止它运行良好。

【讨论】: