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

 更新时间:2020年06月03日 09:01:40   作者:hw_owen ·  
这篇文章主要介绍了python golang中grpc 使用,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

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安装了哪些包

    这篇文章主要给大家介绍了关于如何查看Python安装了哪些包的相关资料, Conda是另一种广泛使用的Python包管理工具,它用于安装、管理和升级软件包和其依赖项,需要的朋友可以参考下
    2023-07-07
  • 如何以Winsows Service方式运行JupyterLab

    如何以Winsows Service方式运行JupyterLab

    这篇文章主要介绍了如何以Winsows Service方式运行JupyterLab的教程
    2020-08-08
  • python matplotlib绘制三维图的示例

    python matplotlib绘制三维图的示例

    这篇文章主要介绍了matplotlib绘制三维图的示例,帮助大家更好的利用python matplotlib绘制图像,感兴趣的朋友可以了解下
    2020-09-09
  • 人脸检测——基于Flask和PaddleHub

    人脸检测——基于Flask和PaddleHub

    这篇文章详细介绍了基于Flask和PaddleHub来进行人脸检测,想详细了解的朋友可以参考阅读
    2023-03-03
  • pandas DataFrame.shift()函数的具体使用

    pandas DataFrame.shift()函数的具体使用

    本文主要介绍了pandas DataFrame.shift()函数的使用,pandas DataFrame.shift()函数可以把数据移动指定的位数,有需要了解pandas DataFrame.shift()用法的朋友可以参考一下
    2021-05-05
  • tensorflow建立一个简单的神经网络的方法

    tensorflow建立一个简单的神经网络的方法

    本篇文章主要介绍了tensorflow建立一个简单的神经网络的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-02-02
  • 一个基于flask的web应用诞生 flask和mysql相连(4)

    一个基于flask的web应用诞生 flask和mysql相连(4)

    一个基于flask的web应用诞生第四篇,这篇文章主要介绍了如何让flask和mysql进行互联,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-04-04
  • C++和python实现阿姆斯特朗数字查找实例代码

    C++和python实现阿姆斯特朗数字查找实例代码

    这篇文章主要给大家介绍了关于C++和python实现阿姆斯特朗数字查找的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • Python多线程中线程数量如何控制

    Python多线程中线程数量如何控制

    本文主要介绍了Python多线程中线程数量如何控制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-01-01
  • python实现画圆功能

    python实现画圆功能

    这篇文章主要为大家详细介绍了python实现画圆功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-01-01

最新评论