gRPC是一款高性能、开源的RPC框架,支持多种编程语言。Protobuf是gRPC使用的默认序化协议,可以将结构化数据序列化为二进制格式,提高数据传输效率

安装第三方包
pip install grpcio

pip install protobuf3

pip install grpcio_tools

创建一个grpc 目录

创建hello_bilibili.proto 文件
syntax = "proto3";

package test;

service Bilibili {
    rpc HellDewei(HelloDeweiReq) returns (HelloDeweiReply) {}
}

message HelloDeweiReq {
    string name = 1;
    int32 age = 2;
}

message HelloDeweiReply {
    string result =1;
}

使用 protoc 编译器和相关的插件来生成Python源代码。如果你已经设置了环境,可以运行如下命令:

python -m grpc_tools.protoc -I ./ --python_out=. --grpc_python_out=. hello_bilibili.proto

这会在当前目录下生成两个文件:hello_bilibili_pb2.py 和 hello_bilibili_pb2_grpc.py。

参数说明:

 python3  -m  grpc_tools.protoc  --python_out=.  --grpc_python_out=.  -I. xxx.proto  -I=/workspace  -I=xxx/yyy/  

  1. -I=:在proto文件中远程调用的内容,导入路径为实际调用的上一级目录即可。 
  2. python_out:指定xxx_pb2.py的输出路径,编译生成处理protobuf相关的代码路径。传入.,则默认生成到当前目录。
  3. grpc_python_out:指定xxx_pb2_grpc.py的输出路径,编译生成处理grpc相关的代码路径,传入.,则默认生成到当前目录。
  4. grpc_tools.protoc:工具包,刚安装的。 
  5. -I:这个参数指定协议文件的查找目录。 

 # 生成的文件中:

  1. xxx_pb2.py:里面有消息序列化类。是用来和protobuf数据进行交互。
  2. xxx_pb2_grpc.py:包含了服务器Stub类和客户端Stub类,以及待实现的服务RPC接口。是用来和grpc进行交互。
创建服务端文件service.python
import grpc
import time
import hello_bilibili_pb2 as pb2
import hello_bilibili_pb2_grpc as pb2_grpc
from concurrent import futures


class Bilibili(pb2_grpc.BilibiliServicer):
    def HellDewei(self, request, context):
        name = request.name
        age = request.age

        result = f"my name is {name}, i am {age} years old"
        return pb2.HelloDeweiReply(result=result)


def run():
    grpc_server = grpc.server(
        futures.ThreadPoolExecutor(max_workers=4)
    )

    pb2_grpc.add_BilibiliServicer_to_server(Bilibili(), grpc_server)
    grpc_server.add_insecure_port("0.0.0.0:5000")
    print("server will start at 0.0.0.0:5000")
    grpc_server.start()
    try:
        while 1:
            time.sleep(3600)
    except KeyboardInterrupt:
        grpc_server.stop(0)


if __name__ == "__main__":
    run()

 然后手动run 起来

创建client.python
import grpc
import hello_bilibili_pb2 as pb2
import hello_bilibili_pb2_grpc as pb2_grpc

def run():
    conn = grpc.insecure_channel('0.0.0.0:5000')
    client = pb2_grpc.BilibiliStub(channel=conn)
    response = client.HellDewei(pb2.HelloDeweiReq(
        name="dewei",
        age=33
    ))
    print(response.result)



if __name__ == "__main__":
    run()

手动run起来

终端显示

my name is dewei, i am 33 years old

参照  https://www.cnblogs.com/sxy-blog/p/1851578

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐