我试图查看是否可以在单个 GRPC 服务器上运行同一服务的不同实例,但看起来我无法这样做。所以我想知道我的测试是否做错了什么,或者根本不可能。
我的测试基于来自 grpc repo的示例/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 的第一个服务,它应该忽略第二个服务实例。
所以,我的问题是,是否有可能在单个服务器上进行这样的操作,如果有一个最佳实践来处理这样的场景,我想要两个几乎相同的服务,参数化不同(例如不同的 grpc 服务器?这意味着负载两个实例之间的平衡)。
在我的特定场景中,要传递的参数是要在服务实现中使用的一些凭据,然后我的目标是让这两个相同的服务同时运行,以便最终用户不知道有多个实例。