多语言通信基础 04 grpc和protobuf

多语言通信基础 04 grpc和protobuf,第1张

gRPC 是一个谷歌开源、高性能、通用的 RPC 框架,面向移动和 HTTP/2 设计。目前提供 C、Java 和 Go 语言版本,分别是:grpc, grpc-java, grpc-go. 其中 C 版本支持 C, C++, Node.js, Python, Ruby, Objective-C, PHP 和 C# 支持。

grpc使用的不是json而是protobuf协议。

protobuf

java中的dubbo使用的协议是 dubbo/rmi/hessian,压缩比会比json高 。常用的协议还有 messagepack压缩比也比json高,如果你懂了协议完全有能力自己去实现一个协议。

  • 习惯用 Json、XML 数据存储格式的你们,相信大多都没听过Protocol Buffer。
  • Protocol Buffer 其实 是 Google出品的一种轻量 & 高效的结构化数据存储格式,性能比 Json、XML 真的强!太!多!
  • protobuf经历了protobuf2和protobuf3,pb3比pb2简化了很多,目前主流的版本是pb3。

protobuf优缺点

protobuf 优点:

  • 性能:压缩性,序列化和反序列化,传输速度好于json和xml
  • 便携性:使用简单,可以自动生成序列化和反序列化代码。向后加绒,添加新内容不用修改旧内容,加密性好。
  • 兼容性:跨语言、跨平台

protobuf 缺点:

  • 通用性差,json任何语言都可以支持,但是protobuf需要专门解析
  • 自解释性差,只有通过proto文件才能了解数据结构
protobuf快速体验  python中体验protobuf3

步骤1:首先安装如下python包。

pip install grpcio
pip install grpcio-tools

步骤2:protobuf3有自己专门的定义方式。

程序示例:

syntax = 'proto3';

message HelloRequest {
    string name = 1;    // name表示名称,name的编号是1
}

图示:pycharm中安装proto插件,就能识别proto文件,如下图

步骤3:进入到文件所在目录执行命令

 python -m grpc_tools.protoc --python_out=. --grpc_python_
out=. -I. .\hello.proto

执行命令后生成两个文件.py如下,两个文件是我们可以使用的python文件:

步骤4:序列化和反序列化

程序示例:

# _*_ coding:utf-8 _*_
__author__ = 'wulian'
__date__ = '2022/4/21 0021 10:39'

import json

from protobuf_test.proto import hello_pb2

# 序列化
request = hello_pb2.HelloRequest()
request.name = "babay"
res_str = request.SerializeToString()   # SerializeToString()是内置序列化方法
print(res_str)  # b'\n\x05babay'

# 反序列化
request2 = hello_pb2.HelloRequest()
request2.ParseFromString(res_str)
print(request2.name)    # babay

# 对比json,proto的压缩比更高
res_json = {
    "name":"babay"
}
print(len(json.dumps(res_json)))    # 17
print(len(res_str))     # 7


运行结果:

b'\n\x05babay'
babay
17
7
python体验grpc开发

我们完整的体验一下python的grpc开发。

步骤1:写proto协议

# 文件:H:\pythonProject\pythonTest\protobuf_grpc\proto\helloWEB.proto

syntax = "proto3";
service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply);
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
    string message = 1;
}

步骤2: 在proto文件路径下,执行命令生成py文件 

python -m grpc_tools.protoc --python_out=. --grpc_python_
out=. -I. .\helloWEB.proto

 步骤3:server端程序

# _*_ coding:utf-8 _*_
__author__ = 'wulian'
__date__ = '2022/4/21 0021 11:31'

from concurrent import futures
import grpc
from protobuf_grpc.proto import helloWEB_pb2, helloWEB_pb2_grpc

class Greeter(helloWEB_pb2_grpc.GreeterServicer):
    def SayHello(self, request, context):
        return helloWEB_pb2.HelloReply(message=f"你好,{request.name}")
if __name__ == "__main__":
    #1.实例化server
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    #2.注册迎辑到server中
    helloWEB_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    #3.启动server
    server.add_insecure_port('0.0.0.0:50051')
    server.start()
    server.wait_for_termination()   # 防止主进程退出

 步骤4:client端程序

# _*_ coding:utf-8 _*_
__author__ = 'wulian'
__date__ = '2022/4/21 0021 11:32'

import grpc
from protobuf_grpc.proto import helloWEB_pb2, helloWEB_pb2_grpc
if __name__ == "__main__":
    # with...as...确保开启关闭
    with grpc.insecure_channel("localhost:50051") as channel:
        stub = helloWEB_pb2_grpc.GreeterStub(channel)
        rsp:helloWEB_pb2.HelloReply = stub.SayHello(helloWEB_pb2.HelloRequest(name="bobby"))
        print(rsp.message)

:步骤5:修改文件的导入

文件:H:\pythonProject\pythonTest\protobuf_grpc\proto\helloWEB_pb2_grpc.py

# import helloWEB_pb2 as helloWEB__pb2
# 修改导入方式,否则service和client无法调用
from protobuf_grpc.proto import helloWEB_pb2 as helloWEB__pb2

步骤6:运行server端和client程序

运行结果:

上面的程序需要注意的就是步骤5修改包的导入,否则运行会出错。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/718526.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-25
下一篇 2022-04-25

发表评论

登录后才能评论

评论列表(0条)

保存