# gRPC 介绍

“gRPC is a modern open source high performance RPC framework that can run in any environment. It can efficiently connect services in and across data centers with pluggable support for load balancing, tracing, health checking and authentication. It is also applicable in last mile of distributed computing to connect devices, mobile applications and browsers to backend services.”

  • On the server side, the server implements this interface and runs a gRPC server to handle client calls.
  • On the client side, the client has a stub (referred to as just a client in some languages) that provides the same methods as the server.

# 环境搭建

  1. 创建一个用于 gRPC 的虚拟环境

    conda create -n grcp_py python=3.10
  2. 激活虚拟环境,并进入到项目目录下方

    conda activate grpc_py
    mkdir grpc
    cd grpc
  3. 安装 gRPC 第三方库及其依赖

    pip install grpcio
    pip install grpcio-tools

# 示例一: HelloWorld

# 功能

  • 客户端调用服务端

# protobuf 协议结构

syntax = "proto3";
package helloworld;
// The greeting service definition.
service Greeter {
  //  远程过程调用的接口
  rpc SayHello (HelloRequest) returns (HelloReply) {}	// 调用 SayHello ()
}
// 交互的消息体
message HelloRequest {
  string name = 1;
}
message HelloReply {
  string message = 1;
}

# 简单的客户端、服务端

  • 服务端
from concurrent import futures	# 提供线程池
import grpc
import helloworld_pb2
import helloworld_pb2_grpc
class Greeter(helloworld_pb2_grpc.GreeterServicer):
    def SayHello(self, request, context):
        return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name)
def serve():
    port = "50051"	# 服务端的端口号
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))	# 创建 grpc 服务端对象
    helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)	# 将重写的服务接口注册到当前服务器上
    server.add_insecure_port("[::]:" + port)	# 设置端口
    server.start()	# 开启服务,多线程开启
    print("Server started, listening on " + port)
    server.wait_for_termination()	# 堵塞
if __name__ == "__main__":
    serve()
  • 客户端
import grpc
import helloworld_pb2
import helloworld_pb2_grpc
def run():
    print("Will try to greet world ...")
    with grpc.insecure_channel("服务端ip:服务端端口") as channel:
        stub = helloworld_pb2_grpc.GreeterStub(channel)		# 调用 GreeterStub 方法去调用远程计算机的 Greeter 服务
        response = stub.SayHello(helloworld_pb2.HelloRequest(name="you"))	# 调用 Greeter 服务下的 SayHello 方法
    print("Greeter client received: " + response.message)
if __name__ == "__main__":
    run()

# with flection

pip install grpcio-reflection
from concurrent import futures
import grpc
from grpc_reflection.v1alpha import reflection
import helloworld_pb2
import helloworld_pb2_grpc
class Greeter(helloworld_pb2_grpc.GreeterServicer):
    def SayHello(self, request, context):
        return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name)
def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    SERVICE_NAMES = (
        helloworld_pb2.DESCRIPTOR.services_by_name["Greeter"].full_name,
        reflection.SERVICE_NAME,
    )
    reflection.enable_server_reflection(SERVICE_NAMES, server)
    server.add_insecure_port("[::]:50051")
    server.start()
    server.wait_for_termination()
if __name__ == "__main__":
    serve()

# 异步客户端、服务端

  • 服务端
import asyncio
import grpc
import helloworld_pb2
import helloworld_pb2_grpc
class Greeter(helloworld_pb2_grpc.GreeterServicer):
    async def SayHello(
        self,
        request: helloworld_pb2.HelloRequest,
        context: grpc.aio.ServicerContext,
    ) -> helloworld_pb2.HelloReply:
        return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name)
async def serve() -> None:
    server = grpc.aio.server()
    helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    listen_addr = "[::]:50051"
    server.add_insecure_port(listen_addr)
    logging.info("Starting server on %s", listen_addr)
    await server.start()
    await server.wait_for_termination()
if __name__ == "__main__":
    asyncio.run(serve())

# 参考

  • [1] gRPC
  • [2] [Github for gRPC][https://github.com/grpc/grpc]
Edited on Views times

Give me a cup of [coffee]~( ̄▽ ̄)~*

Value WeChat Pay

WeChat Pay