如何在Scala中使用Google pubsub库

时间:2018-07-02 14:05:07

标签: scala functional-programming google-cloud-pubsub

我正在使用Java API编写Google pubsub客户端,该客户端是用Scala编写的。该代码的问题在于,使用nullwhile true循环在Scala中不是惯用语言

 val receiver = new MessageReceiver() {
      // React to each received message
      // If there are any
      override def receiveMessage(message: PubsubMessage, consumer: AckReplyConsumer): Unit = { // handle incoming message, then ack/nack the received message
        System.out.println("Id : " + message.getMessageId)
        System.out.println("Data : " + message.getData.toStringUtf8)
        throw new RuntimeException("This is just an exception")
        consumer.ack()
      }
    }

var subscriber: ApiService = null
    try { // Create a subscriber for "my-subscription-id" bound to the message receiver
      var subscriber = Subscriber.newBuilder(subscriptionName, receiver).build
      subscriber.startAsync
      // ...
    } finally {
      // stop receiving messages
      if (subscriber != null) subscriber.stopAsync()
    }
while (true) {
    Thread.sleep(1000)
}

如何转换此代码以使用scala的Future或cat IO

2 个答案:

答案 0 :(得分:1)

您是否考虑过使用Lightbend的Alpakka Google Cloud Pub / Sub连接器? https://developer.lightbend.com/docs/alpakka/current/google-cloud-pub-sub.html

效果很好,很惯用

答案 1 :(得分:0)

有一个cats风格的Pub / Sub Scala客户端-https://github.com/hyjay/fs2-google-cloud-pubsub

免责声明:我是作者。