是否可以在单个GRPC服务器上运行同一服务的多个实例?

时间:2020-04-30 16:21:08

标签: python grpc protobuf-python

我试图查看是否可以在单个GRPC服务器上运行同一服务的不同实例,但是看来我无法这样做。所以我想知道我的测试是否做错了什么,还是根本不可能做?

我的测试基于来自grpc仓库的examples/python/multiplex

服务:

class _GreeterServicer(helloworld_pb2_grpc.GreeterServicer):

    def __init__(self, greeter):
        self.greeter = greeter

    def SayHello(self, request, context):
        return helloworld_pb2.HelloReply(
            message='Hello, {}! This is {}!'.format(request.name, self.greeter))

服务器:

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    helloworld_pb2_grpc.add_GreeterServicer_to_server(_GreeterServicer("John"),
                                                      server)
    helloworld_pb2_grpc.add_GreeterServicer_to_server(_GreeterServicer("Jim"),
                                                      server)
    server.add_insecure_port('[::]:50051')
    server.start()
    server.wait_for_termination()

客户:

def run():
    for _ in range(10):
        with grpc.insecure_channel('localhost:50051') as channel:
            greeter_stub = helloworld_pb2_grpc.GreeterStub(channel)
            greeter_response = greeter_stub.SayHello(
                helloworld_pb2.HelloRequest(name='you'))
            print("Greeter client received: " + greeter_response.message)

由于我为每次迭代都打开了一个新通道,所以我期望得到的输出是“你好,你!我是吉姆!”和“你好,你!我是约翰!”,但我只知道:

Greeter client received: Hello, you! This is John!
Greeter client received: Hello, you! This is John!
Greeter client received: Hello, you! This is John!
Greeter client received: Hello, you! This is John!
Greeter client received: Hello, you! This is John!
Greeter client received: Hello, you! This is John!
Greeter client received: Hello, you! This is John!
Greeter client received: Hello, you! This is John!
Greeter client received: Hello, you! This is John!
Greeter client received: Hello, you! This is John!

,即我添加到服务器的GreeterServicer的第一个服务,它应该忽略了第二个servicer实例。

所以,我的问题是,是否可以在单个服务器上进行类似的操作,是否有最佳实践来处理这样的场景,即我想要两个参数完全相同但参数不同的服务(例如,不同的grpc服务器?表示两个实例之间的负载平衡)。

在我的特定情况下,要传递的参数是要在服务实现中使用的一些凭据,然后我的目标是让这两个相同的服务同时运行,以便最终用户不知道有多个实例。

1 个答案:

答案 0 :(得分:1)

gRPC-Go实现显式禁止在grpc.Server对象上多次注册同一服务。 Code

我对Python的实现不是很熟悉,但是我认为它也做了类似的事情。对add_GreeterServicer_to_server的调用是否返回状态或错误?