python golang中grpc 使用示例代码详解


Posted in Python onJune 03, 2020

python

1、使用前准备,安装这三个库

pip install grpcio
pip install protobuf
pip install grpcio_tools

2、建立一个proto文件hello.proto

// [python quickstart](https://grpc.io/docs/quickstart/python.html#run-a-grpc-application)
// python -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I. hello.proto

// helloworld.proto
syntax = "proto3";
package test;

service Greeter {
 rpc SayHello(HelloRequest) returns (HelloReply) {}
 rpc SayHelloAgain(HelloRequest) returns (HelloReply) {}

}
service Greetera{
 rpc SayStudent(Studentid) returns (Student){}
}
message Student {
 string msg=1;//json
}


message Studentid{
 string id=1;
}
message HelloRequest {
 string name = 1;
}

message HelloReply {
 string message = 1;
}

3、执行命令就会对应生成两个py文件

hello_pb2.py

hello_pb2_grpc.py

python -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I. hello.proto

4、py服务端代码hello.server.py:

from concurrent import futures
import time
import grpc
import hello_pb2
import hello_pb2_grpc
import json
# 实现 proto 文件中定义的 GreeterServicer
class Greeter(hello_pb2_grpc.GreeterServicer):
 # 实现 proto 文件中定义的 rpc 调用
 def SayHello(self, request, context):
 return hello_pb2.HelloReply(message = 'hello {msg}'.format(msg = request.name))
 def SayHelloAgain(self, request, context):
 return hello_pb2.HelloReply(message='hello {msg}'.format(msg = request.name))

class Gretera(hello_pb2_grpc.GreeteraServicer):
 def SayStudent(self,request,context):
 print(request.id)
 if request.id=="0":
 c=hello_pb2.Student(msg=json.dumps({"name":"owen","age":22,"sex":"男"}))
 else:
 c=hello_pb2.Student(msg=json.dumps({"name":"lihui","age":23,"sex":"女"}))
 return c
def serve():
 # 启动 rpc 服务
 server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
 hello_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
 hello_pb2_grpc.add_GreeteraServicer_to_server(Gretera(),server)
 server.add_insecure_port('[::]:50052')
 server.start()
 try:
 while True:
 time.sleep(60*60*24) # one day in seconds
 except KeyboardInterrupt:
 server.stop(0)
if __name__ == '__main__':
 serve()

py客户端代码hello.client.py:

import grpc
import hello_pb2
import hello_pb2_grpc
import json
def run():
 # 连接 rpc 服务器
 channel = grpc.insecure_channel('localhost:50051')
 # 调用 rpc 服务
 stub = hello_pb2_grpc.GreeterStub(channel)
 response = stub.SayHello(hello_pb2.HelloRequest(name='czl'))
 print("Greeter client received: " + response.message)
 response = stub.SayHelloAgain(hello_pb2.HelloRequest(name='nsdnfkjda'))
 print("Greeter client received: " + response.message)
 stub1 = hello_pb2_grpc.GreeteraStub(channel)
 response1 = stub1.SayStudent(hello_pb2.Studentid(id='1'))
 print(json.loads(response1.msg))
if __name__ == '__main__':
 run()

golang

由于grpc是跨语言的所以这里用golang做为示范,golang客户端代码,小编这里也踩了许多坑,最主要的是两个proto文件一定要一致,golang 中使用必须安装protoc,windows将环境变量指向安装目录的bin下面:

1、protocal buffer安装

从 https://github.com/google/protobuf/releases  下载 对应自己的系统(环境变量记得改)

2、安装 golang protobuf

go get -u github.com/golang/protobuf/proto // golang protobuf 库
go get -u github.com/golang/protobuf/protoc-gen-go //protoc --go_out 工具

3、安装 gRPC-go

go get google.golang.org/grpc

4、生成go文件

protoc --go_out=plugins=grpc:文件目录 对应的.proto文件
protoc --go_out=plugins=grpc:. hello.proto

生成hello.pb.go,调用的实现hello_go_client.go:

package main
import (
 "context"
 "encoding/json"
 "google.golang.org/grpc"
 "log"
 "student/test" //对应的生成文件目录
)
type Studenmsg struct {
 Name string
 Age int
 Sex string
}
func main() {
 // 建立连接到gRPC服务
 conn, err := grpc.Dial("127.0.0.1:50052", grpc.WithInsecure())
 if err != nil {
 log.Fatalf("did not connect: %v", err)
 }
 // 函数结束时关闭连接
 defer conn.Close()
 // 创建Waiter服务的客户端
 t := test.NewGreeteraClient(conn)
 tr,err:=t.SayStudent(context.Background(),&test.Studentid{Id:"1"})
 if err != nil {
 log.Fatalf("could not greet: %v", err)
 }
 var st Studenmsg
 err=json.Unmarshal([]byte(tr.Msg),&st)//这里说明一下发过来的数据是json格式转化成struct
 if err!=nil{
 log.Println(err.Error())
 }
 log.Println(st.Name,st.Age,st.Sex)
}

总结

到此这篇关于python golang中grpc 使用示例代码详解的文章就介绍到这了,更多相关python golang grpc 使用内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python列表与元组详解实例
Nov 01 Python
浅要分析Python程序与C程序的结合使用
Apr 07 Python
Python HTMLParser模块解析html获取url实例
Apr 08 Python
python使用htmllib分析网页内容的方法
May 08 Python
python实现图书管理系统
Mar 12 Python
Django实现分页功能
Jul 02 Python
Python根据欧拉角求旋转矩阵的实例
Jan 28 Python
python使用minimax算法实现五子棋
Jul 29 Python
pycharm工具连接mysql数据库失败问题
Apr 01 Python
Python类中的装饰器在当前类中的声明与调用详解
Apr 15 Python
Python调用Redis的示例代码
Nov 24 Python
Pycharm 跳转回之前所在页面的操作
Feb 05 Python
Opencv图像处理:如何判断图片里某个颜色值占的比例
Jun 03 #Python
QML用PathView实现轮播图
Jun 03 #Python
Python基于smtplib协议实现发送邮件
Jun 03 #Python
Pytorch环境搭建与基本语法
Jun 03 #Python
如何学习Python time模块
Jun 03 #Python
使用openCV去除文字中乱入的线条实例
Jun 02 #Python
Python能做什么
Jun 02 #Python
You might like
推荐几部必看的DC动画电影
2020/03/03 欧美动漫
很好用的PHP数据库类
2009/05/27 PHP
php文件上传的两种实现方法
2016/04/04 PHP
PHP配合fiddler抓包抓取微信指数小程序数据的实现方法分析
2020/01/02 PHP
window.open以post方式将内容提交到新窗口
2012/12/26 Javascript
jquery.ajax的url中传递中文乱码问题的解决方法
2014/02/07 Javascript
node.js中的fs.readdir方法使用说明
2014/12/17 Javascript
浅谈关于JavaScript API设计的一些建议和准则
2015/06/24 Javascript
js实现当复选框选择匿名登录时隐藏登录框效果
2015/08/14 Javascript
逐一介绍Jquery data()、Jquery stop()、jquery delay()函数(详)
2015/11/04 Javascript
基于jQuery实现Ajax验证用户名是否存在实例
2016/03/30 Javascript
Angularjs 实现分页功能及示例代码
2016/09/14 Javascript
JavaScript“尽快失败”的原则实例详解
2016/10/08 Javascript
laydate.js日期时间选择插件
2017/01/04 Javascript
Textarea输入字数限制实例(兼容iOS&安卓)
2017/07/06 Javascript
HTML元素拖拽功能实现的完整实例
2020/12/04 Javascript
python通过自定义isnumber函数判断字符串是否为数字的方法
2015/04/23 Python
python中利用xml.dom模块解析xml的方法教程
2017/05/24 Python
浅谈对yield的初步理解
2017/05/29 Python
python 对txt中每行内容进行批量替换的方法
2018/07/11 Python
详解django+django-celery+celery的整合实战
2019/03/19 Python
使用Python paramiko模块利用多线程实现ssh并发执行操作
2019/12/05 Python
python输出pdf文档的实例
2020/02/13 Python
浅谈python元素如何去重,去重后如何保持原来元素的顺序不变
2020/02/28 Python
日常奢侈品,轻松购物:Verishop
2019/08/20 全球购物
机械制造与自动化应届生求职信
2013/11/16 职场文书
工程资料员岗位职责
2014/03/10 职场文书
旅游与环境专业求职信
2014/06/05 职场文书
法人授权委托书样本
2014/09/19 职场文书
2014年生产部工作总结
2014/12/17 职场文书
高考升学宴答谢词
2015/01/20 职场文书
大学生个人简历自我评价
2015/03/11 职场文书
2015年双拥工作总结
2015/04/08 职场文书
自制短波长线天线频率预选器 - 成功消除B2K之流的镜像
2021/04/22 无线电
忆童年!用Python实现愤怒的小鸟游戏
2021/06/07 Python
MySQL一劳永逸永久支持输入中文的方法实例
2022/08/05 MySQL