首页 > 解决方案 > 跟踪 grpc 服务器上的多个客户端

问题描述

我正在尝试创建一个grpc可以跟踪所有连接的客户端的 python 服务器。

我指的是 Ray Tsang 所做的一个谈话/演示,他保存了一个集合StreamObservers并只是迭代它们以发送给所有客户。这是一个视频供参考。

现在我的问题是你如何StreamObserver在 python 中得到一个?我只看到self,request并且context在定义中对我可用。

这是我的第一个 python 项目,所以我可能在这里遗漏了一些明显的东西。

这是我的原型,它基本上是示例原型

syntax = "proto3";

package hellostreamingworld;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
  // Sends another greeting
  rpc SayHelloAgain (HelloRequest) returns (stream HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

标签: pythongrpcgrpc-python

解决方案


如果我了解您需要创建一个扩展 grpc.UnaryUnaryClientInterceptor 的类 ClientInterceptor(https://grpc.io/grpc/python/grpc.html?highlight=unaryunaryclientinterceptor#grpc.UnaryUnaryClientInterceptor),然后用intercept_channel方法分配它这边走

self.channel = grpc.insecure_channel(address, options)

self.channel = grpc.intercept_channel(
     self.channel,
     ClientInterceptor()
)

您可以使用 intercept_unary_unary 方法接收有关各种客户端的信息。

如果您想让 infos 服务器端扩展 ServerInterceptor(https://grpc.io/grpc/python/grpc.html?highlight=serverinterceptor#grpc.ServerInterceptor)并在服务器初始化时分配它

self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=1000),
                          options=(('grpc.max_send_message_length', 1000 * 1024 * 1024,),
                                   ('grpc.max_receive_message_length', 1000 * 1024 * 1024,),
                                  ),
                          interceptors=(MyServerInterceptor())
                         )

并使用 intercept_service 方法接收信息。


推荐阅读