Scala Grpc 失败,出现错误 io.grpc.StatusRuntimeException:取消:无法读取消息

Scala Grpc failed with error io.grpc.StatusRuntimeException: CANCELLED: Failed to read message

我正在尝试使用 GRPC 在 Scala 中编写流媒体服务。为此,我写了这个原型文件

syntax = "proto3";
package com.abhi.grpc;

message TimeRequest{}
message TimeResponse {
    int64 currentTime = 1;
}

service Clock {
    rpc StreamTime(TimeRequest) returns (stream TimeResponse);
}

这是我的服务器端代码

import com.abhi.grpc.clock.{ClockGrpc, TimeRequest, TimeResponse}
import io.grpc.stub.StreamObserver
import monix.execution.Scheduler
import monix.execution.Scheduler.{global => scheduler}
import scala.concurrent.duration._

object ClockGrpcServer extends GrpcServer with App {
   val ssd = ClockGrpc.bindService(new ClockGRPC(), Scheduler.global)
   runServer(ssd, "Clock")
}

class ClockGRPC extends ClockGrpc.Clock {
   override def streamTime(request: TimeRequest, responseObserver: StreamObserver[TimeResponse]): Unit = {
      scheduler.scheduleWithFixedDelay(0.seconds, 3.seconds) {
         responseObserver.onNext(TimeResponse(System.currentTimeMillis))
      }
   }
}

这是我的客户

object ClockGrpcClient extends App {
   val channel = ManagedChannelBuilder.forAddress("localhost", 50051).usePlaintext(true).build()
   val stub = ClockGrpc.stub(channel)
   val observer = new StreamObserver[TimeResponse] {
      override def onError(t: Throwable): Unit = println(s"failed with error ${t}")
      override def onCompleted(): Unit = println("closing observer")
      override def onNext(value: TimeResponse): Unit = println(s"received time ${new DateTime(value)}")
   }
   stub.streamTime(TimeRequest(), observer)
   StdIn.readLine()
}

当我运行服务器和客户端。服务器一收到来自客户端的任何消息就抛出以下错误

io.grpc.StatusRuntimeException: CANCELLED
        at io.grpc.Status.asRuntimeException(Status.java:534)
        at io.grpc.stub.ServerCalls$ServerCallStreamObserverImpl.onNext(ServerCalls.java:279)
        at com.abhi.ClockGRPC.$anonfun$streamTime(ClockGRPC.scala:22)
        at monix.execution.internal.RunnableAction.run(RunnableAction.scala:25)
        at monix.execution.schedulers.ReferenceScheduler$$anon.run(ReferenceScheduler.scala:45)
        at scala.concurrent.impl.ExecutionContextImpl$AdaptedForkJoinTask.exec(ExecutionContextImpl.scala:140)
        at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
        at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
        at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
        at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)

我用谷歌搜索了一下,找到了这篇文章

https://blog.codecentric.de/en/2017/01/hello-grpc-scalapb/

基于此,我将服务器更改为使用 java.util 调度程序

class ClockGRPC extends ClockGrpc.Clock {
   val scheduler = Executors.newSingleThreadScheduledExecutor()
   override def streamTime(request: TimeRequest, responseObserver: StreamObserver[TimeResponse]): Unit = {
      val tick = new Runnable {
         val counter = new AtomicInteger(10)
         def run() =
            if (counter.getAndDecrement() >= 0) {
               val currentTime = System.currentTimeMillis()
               responseObserver.onNext(TimeResponse(currentTime))
            } else {
               scheduler.shutdown()
               responseObserver.onCompleted()
            }
      }
      scheduler.scheduleAtFixedRate(tick, 0l, 3000l, TimeUnit.SECONDS)
   }
}

但我仍然收到已取消的错误。所以我无法让流媒体示例工作。

这个问题我差点放弃了。不过今天回来解决了。

问题出在

override def onNext(value: TimeResponse): Unit = println(s"received time ${new DateTime(value)}")

值无法传递给 new DateTime

雪上加霜。如果异常发生在回调方法中。 Grpc 吞下它并用通用错误消息替换它

info] Running com.abhi.ClockGrpcClient failed with error io.grpc.StatusRuntimeException: CANCELLED: Failed to read message.

运气不好,他的DateTime使用了一个对象作为参数,所以编译成功了,但是运行时调用失败,异常被grpc吞掉了。

我把它留在这里是为了帮助其他人。

[info] Running com.abhi.ClockGrpcClient failed with error io.grpc.StatusRuntimeException: CANCELLED: Failed to read message

说明回调函数出错了