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爬虫基本知识
Mar 05 Python
python求最大连续子数组的和
Jul 07 Python
python版本五子棋的实现代码
Dec 11 Python
Python中new方法的详解
Jan 15 Python
使用python itchat包爬取微信好友头像形成矩形头像集的方法
Feb 21 Python
值得收藏的10道python 面试题
Apr 15 Python
pycharm配置当鼠标悬停时快速提示方法参数
Jul 31 Python
python pyinstaller打包exe报错的解决方法
Nov 02 Python
基于Tensorflow:CPU性能分析
Feb 10 Python
python 使用cx-freeze打包程序的实现
Mar 14 Python
10个python爬虫入门实例(小结)
Nov 01 Python
Python实现邮件发送的详细设置方法(遇到问题)
Jan 18 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
解析php取整的几种方式
2013/06/25 PHP
yii框架builder、update、delete使用方法
2014/04/30 PHP
PHP+ajax实现上传、删除、修改单张图片及后台处理逻辑操作详解
2020/02/12 PHP
向fckeditor编辑器插入指定代码的方法
2007/05/25 Javascript
javascript json 新手入门文档
2009/12/03 Javascript
JS中setTimeout的巧妙用法前端函数节流
2016/03/24 Javascript
jQuery实时显示鼠标指针位置和键盘ASCII码
2016/03/28 Javascript
Ionic如何实现下拉刷新与上拉加载功能
2016/06/03 Javascript
AngularJS中一般函数参数传递用法分析
2016/11/22 Javascript
浅析JS中的 map, filter, some, every, forEach, for in, for of 用法总结
2017/03/29 Javascript
JavaScript模块化之使用requireJS按需加载
2017/04/12 Javascript
详解vue2父组件传递props异步数据到子组件的问题
2017/06/29 Javascript
vue样式穿透 ::v-deep的具体使用
2020/06/04 Javascript
python下如何让web元素的生成更简单的分析
2008/07/17 Python
使用Python开发windows GUI程序入门实例
2014/10/23 Python
Python2.6版本中实现字典推导 PEP 274(Dict Comprehensions)
2015/04/28 Python
使用Mixin设计模式进行Python编程的方法讲解
2016/06/21 Python
Python字典,函数,全局变量代码解析
2017/12/18 Python
对Python3中的input函数详解
2018/04/22 Python
用python画一只可爱的皮卡丘实例
2019/11/21 Python
python输出pdf文档的实例
2020/02/13 Python
如何使用Python抓取网页tag操作
2020/02/14 Python
完美解决Django2.0中models下的ForeignKey()问题
2020/05/19 Python
python和opencv构建运动检测器的实现
2021/03/03 Python
CSS3 text shadow字体阴影效果
2016/01/08 HTML / CSS
请写出 float x 与"零值"比较的 if 语句
2016/01/04 面试题
学校社会实践活动总结
2014/07/03 职场文书
大学生入党积极分子党校学习思想汇报
2014/10/25 职场文书
个人股份转让协议书范本
2014/10/26 职场文书
银行求职信范文怎么写
2015/03/20 职场文书
党小组鉴定意见
2015/06/02 职场文书
商务信函英语问候语
2015/11/10 职场文书
2019学校请假条格式及范文
2019/06/25 职场文书
浅谈Python项目的服务器部署
2021/04/25 Python
pytorch中F.avg_pool1d()和F.avg_pool2d()的使用操作
2021/05/22 Python
Python实现自动玩连连看的脚本分享
2022/04/04 Python