当前位置:网站首页>多语言通信基础 04 grpc和protobuf
多语言通信基础 04 grpc和protobuf
2022-04-21 16:48:00 【一越王超】
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://yiyuewangchao.blog.csdn.net/article/details/124313931
边栏推荐
- 吴恩达机器学习详细总结(三)
- 易鲸捷数据库将获得中国软件投资,不超过3.89亿元
- 微软IE本地文件读取漏洞
- Summary of Wu Enda's course of machine learning (5)
- 携程网主站XSS漏洞
- Program design TIANTI race l3-29 restore file (DFS is over, leaving the original spectrum)
- 疫情催化下,毫末智行这款产品为何能推动自动配送商业化加速?
- PPLive website has a storage type cross site scripting vulnerability
- Use of Arthas tunnel
- 手机软硬件协同很重要吗?
猜你喜欢

Tuojing technology landed on the science and Innovation Board: raised about 2.3 billion yuan, with a total market value of more than 10 billion yuan

C sliding verification code | puzzle verification | slidecaptcha

如果这题都不会面试官还会继续问我 JVM 嘛:如何判断对象是否可回收

拓荆科技登陆科创板:募资约23亿元,总市值突破100亿元

【观察】紫光云:同构混合云升级为分布式云,让云和智能无处不在

How to judge whether a binary differential equation is a total differential

2018-8-10-use-resharper-features

2018-8-10-使用-Resharper-特性

中国创投,凛冬将至

C语言程序的环境,编译+链接
随机推荐
sqli-labs 23-25a关闯关心得与思路
elmentUI表单中input 和select长度不一致问题
微软IE本地文件探测漏洞
30. 构造方法的重载
What are the similarities and differences between LCD and OLED screens
MongoDB安全配置
2-4. Port binding
OTS parsing error: invalid version tag解决方法
Sogou website divulges information
SQL -- database operation (DDL, DML, DQL) + use the command to view the storage location of the current database (database version query)
Database Principle -- library management system
js 毫秒转天时分秒
SSH implementation of remote login server
手机软硬件协同很重要吗?
Tuojing technology landed on the science and Innovation Board: raised about 2.3 billion yuan, with a total market value of more than 10 billion yuan
IvorySQL亮相于PostgresConf SV 2022 硅谷Postgres大会
IOS development interview strategy (KVO, KVC, multithreading, lock, runloop, timer)
遨游浏览器本地跨站脚本漏洞
高数 | 【多元函数微分学】如何判断二元微分式是否为全微分
Outsourcing student management system detailed architecture design document


