以下是一个使用Docker和gRPC的简单服务端示例:

首先,创建一个Dockerfile,用于构建镜像。

FROM python:3.8-slim-buster

WORKDIR /app

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD [ "python", "./server.py" ]

然后,创建一个server.py文件,用于实现gRPC服务端。

import grpc
import time

from concurrent import futures

import hello_pb2
import hello_pb2_grpc

class Greeter(hello_pb2_grpc.GreeterServicer):
    def SayHello(self, request, context):
        return hello_pb2.HelloReply(message=f"Hello, {request.name}!")

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    hello_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    server.add_insecure_port("[::]:50051")
    server.start()
    print("Server started on port 50051")
    try:
        while True:
            time.sleep(60 * 60 * 24)
    except KeyboardInterrupt:
        server.stop(0)

if __name__ == "__main__":
    serve()

最后,创建一个requirements.txt文件,用于安装gRPC和protobuf库。

grpcio
protobuf

使用以下命令构建和运行Docker容器:

docker build -t grpc-server .
docker run -p 50051:50051 grpc-server

现在,您可以使用任何gRPC客户端(例如,通过Python gRPC库)来连接到服务端并发送请求。

参考资料:

  • https://grpc.io/docs/languages/python/quickstart/
  • https://docs.docker.com/language/python/build-images/
在github上找一个服务端docker服务通过grpc请求的例子

原文地址: http://www.cveoy.top/t/topic/BAt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录