grpc实例之Python实现

grpc实例之Python实现
grpc实例之C++实现
grpc详解和安装
本此实例的目的就是客户端给服务端传递三个参数, string, int32, double三种类型, 在从服务端读取到上面三种类型

首先看一下效果

在这里插入图片描述

在这里插入图片描述

安装Python环境

conda create -n grpc python=3.6
conda activate grpc
pip install grpcio==1.12.0
pip install grpcio-tools==1.12.0

一. 创建配置文件(极其简单)

  • 找一个空文件夹, 随意起名, 这里用msg.proto
  • 该文件定义的就是请求和相应的模板, 其中包含请求的函数名称, 请求函数的入口参数, 返回参数
// 目的是设计一个单一请求, 单一回应的服务, 类似于函数调用, 如下注释所示
// GetMsg(MsgRequest:dict) -> dict:
//     ...
//     return MsgResponse
syntax = "proto3"; // 规定使用proto3的语法
service MsgService { // 定义服务, 流数据放到括号里面
	rpc GetMsg (MsgRequest) returns (MsgResponse){}
}
 
message MsgRequest { // 请求的结构, 也可以定义int32,int64,double,float等数据类型, 等号后面的数字表示第几个
	string name = 1;
	int32 num1 = 2;
	double num2 = 3;
}
 
message MsgResponse { // 回应的结果
	string msg = 1;
	int32 num1 = 2;
	double num2 = 3;
}

上面的伪代码如下所示

class MsgService
{
public:
	dict GetMsg(string name, int32 num1, double num2){
		res = {string msg, int32 num1, double num2};
		res = handle(name, num1, num2, res);
		return res;
	}
};

二. 生成Python头文件

运行下面指令即可
python -m grpc_tools.protoc -I . --python_out=. --grpc_python_out=. msg.proto
运行完成后会生成下面两个文件

├── msg.proto
├── msg_pb2.py
├── msg_pb2_grpc.py

三. 服务器端

import grpc
import msg_pb2
import msg_pb2_grpc

# 因为 RPC 应该长时间运行,考虑到性能,还需要用到并发的库。
import time # 设置系统延时,
from concurrent import futures
_ONE_DAY_IN_SECONDS = 60 * 60 * 24 # 设置服务器运行的默认时间长度

# 按照msg.proto中定义的, 将类实现了
# 这里GetMsg就是msg.proto定义的服务端函数, 
# rpc GetMsg (MsgRequest) returns (MsgResponse){}
# GetMsg 接收到的请求是在 request 中
# msg.proto 中定义的 name 就是 request.name
# 接着在 GetMsg 中设计 msg.proto 中定义的 MsgResponse

# 其实相当于实现这个类这个函数即可
class MsgServicer(msg_pb2_grpc.MsgServiceServicer):
	def GetMsg(self, request, context):
		print(f"Received name = {request.name} num1={request.num1}, num2={request.num2}") # 客户端请求的数据
		return msg_pb2.MsgResponse(msg='Hello, %s!' % request.name, num1=23, num2=2.026) # 返回的参数赋值

def myserver():
	server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))  # 设置最大连接数
	msg_pb2_grpc.add_MsgServiceServicer_to_server(MsgServicer(), server)  #
	server.add_insecure_port('[::]:50051') # 设置所有IP地址都可以访问, 端口号为50051
	server.start() # 启动服务
	
	try:
		while True:
			time.sleep(_ONE_DAY_IN_SECONDS)# 设置服务器启动一天, 一天后自动关闭
			print("时间到了, 该结束了") 
	except KeyboardInterrupt: # 如果出现ctr+c硬中断, 直接退出
		server.stop(0)

if __name__ == "__main__":
	myserver()

四. 客户端

import grpc
 
import msg_pb2
import msg_pb2_grpc
 
def run():
	# NOTE(gRPC Python Team): .close() is possible on a channel and should be
	# used in circumstances in which the with statement does not fit the needs
	# of the code.
	with grpc.insecure_channel('localhost:50051') as channel:
		stub = msg_pb2_grpc.MsgServiceStub(channel)
		response = stub.GetMsg(msg_pb2.MsgRequest(name='world', num1=32, num2=3.435)) # 这是请求的数据给服务端, 然后在读取服务端返回来的数据
		print(f"Client received: {response.msg}, num1 = {response.num1}, num2 = {response.num2}")
if __name__ == '__main__':
  run()

总结:
逻辑上就是利用工具, 对配置好的函数模板, 生成一套头文件, 然后在通过调用和重写
就可以实现C/S 请求和响应操作了.

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落子无悔!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值