Google Pub / Sub订阅者不会收到消息?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (212)

我的代码如下所示,基本上与示例中的代码完全相同:

package com.example.google.pubsub

import java.io.FileInputStream
import java.security.spec.PKCS8EncodedKeySpec
import java.security.{KeyFactory, PrivateKey}
import java.util.Base64

import akka.actor.ActorSystem
import akka.stream.{ActorMaterializer, Attributes, Outlet, SourceShape}
import akka.stream.alpakka.googlecloud.pubsub.scaladsl.GooglePubSub
import akka.stream.alpakka.googlecloud.pubsub._
import akka.stream.scaladsl.{Sink, Source}
import akka.stream.stage.{GraphStage, GraphStageLogic}
import akka.{Done, NotUsed}
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential

import scala.concurrent.duration._
import scala.concurrent.Future

object SubscriberMain extends App {
  println("#### SUBSCRIBER ####")

  val privateKey: PrivateKey = {
    import java.io.FileInputStream
    val credential = GoogleCredential.fromStream(new FileInputStream("mycredentials.json"))
    val privateKey = credential.getServiceAccountPrivateKey
    privateKey
  }
  val clientEmail = "main-19@weirdproject.iam.gserviceaccount.com"
  val projectId = "weirdproject"
  val apiKey = "xxxx"
  val subscription = "somesubscription"

  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()

  val subscriptionSource: Source[ReceivedMessage, NotUsed] =
    GooglePubSub.subscribe(projectId, apiKey, clientEmail, privateKey, subscription)

  val ackSink: Sink[AcknowledgeRequest, Future[Done]] =
    GooglePubSub.acknowledge(projectId, apiKey, clientEmail, privateKey, subscription)

  subscriptionSource
    .map { message =>
      val data = message.message.data
      println(s"received a message: $data")
      message.ackId
    }
    .groupedWithin(1000, 1.minute)
    .map(AcknowledgeRequest.apply)
    .to(ackSink)

}

我发现akka.stream.alpakka.googlecloud.pubsub.GooglePubSubSource.createLogic从未被执行,这似乎是没有提取消息的原因。

提问于
用户回答回答于

你有什么是一个流的定义,但你没有运行它。调用run()

subscriptionSource
  .map { message =>
    val data = message.message.data
    println(s"received a message: $data")
    message.ackId
  }
  .groupedWithin(1000, 1.minute)
  .map(AcknowledgeRequest.apply)
  .to(ackSink)
  .run() // <---

或使用runWith(),这是一种方便的方法,可返回以下物化值Sink

val result: Future[Done] =
  subscriptionSource
    .map { message =>
      val data = message.message.data
      println(s"received a message: $data")
      message.ackId
    }
    .groupedWithin(1000, 1.minute)
    .map(AcknowledgeRequest.apply)
    .runWith(ackSink)

扫码关注云+社区

领取腾讯云代金券