python实现grpc客户端服务端多进程并发执行
时间: 2023-07-25 12:38:19 浏览: 717
下面是一个简单的Python代码示例,演示如何使用gRPC实现客户端和服务端的多进程并发执行:
服务端代码:
```python
import grpc
from concurrent import futures
import time
import hello_pb2
import hello_pb2_grpc
class HelloService(hello_pb2_grpc.HelloServicer):
def sayHello(self, request, context):
print("Received message: ", request.message)
return hello_pb2.HelloReply(message="Hello, %s!" % request.message)
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
hello_pb2_grpc.add_HelloServicer_to_server(HelloService(), server)
server.add_insecure_port("[::]:50051")
server.start()
print("Server started at [::]:50051")
while True:
time.sleep(86400)
if __name__ == '__main__':
serve()
```
客户端代码:
```python
import grpc
import hello_pb2
import hello_pb2_grpc
from concurrent import futures
import multiprocessing
def run_client():
channel = grpc.insecure_channel("localhost:50051")
stub = hello_pb2_grpc.HelloStub(channel)
response = stub.sayHello(hello_pb2.HelloRequest(message="world"))
print("Response received from server: ", response.message)
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=4)
for i in range(4):
pool.apply_async(run_client)
pool.close()
pool.join()
```
在上面的示例中,服务端使用了Python的concurrent.futures模块创建了一个线程池,用于处理客户端的请求,同时使用了Python的multiprocessing模块创建了多个子进程,同时向服务端发起请求。客户端通过调用multiprocessing.Pool()方法创建进程池,并使用apply_async()方法异步调用run_client()方法,实现了多个客户端同时向服务端发起请求的并发执行。
阅读全文