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 golang中grpc 使用示例代码详解的更多相关文章

  1. C#中异步调用示例与详解

    using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServi ...

  2. 第8.13节 Python类中内置方法__repr__详解

    当我们在交互环境下输入对象时会直接显示对象的信息,交互环境下输入print(对象)或代码中print(对象)也会输出对象的信息,这些输出信息与两个内置方法:__str__方法和__repr__方法有关 ...

  3. (Go)07.Go语言中strings和strconv包示例代码详解02

    1.strings使用 统计字符串出现次数 strings.Count(s string, substr string) int Count 用于计算字符串 substr 在字符串 s 中出现的非重叠 ...

  4. (Go)07.Go语言中strings和strconv包示例代码详解01

    1.strings使用 前缀和后缀 HasPrefix判断字符串s是否以prefix开头: 示例: package main import ( "fmt" "string ...

  5. 第8.14节 Python类中内置方法__str__详解

    一. object类内置方法__str__和函数str 类的内置方法__str__和内置函数str实际上实现的是同一功能,实际上str调用的就是__str__方法,只是调用方式不同,二者的调用语法如下 ...

  6. vue-cli中进行微信支付代码详解

    最近做微信支付,颇经历一番波折,这里总结一下,便于以后少走弯路: 在进行微信支付,除了需要公众号之外,你还需要一个微信商户.根据商户规则进行商户申请 这是公众号的基本开发配置,这里在微信授权的时候就已 ...

  7. **Python中的深拷贝和浅拷贝详解

    Python中的深拷贝和浅拷贝详解   这篇文章主要介绍了Python中的深拷贝和浅拷贝详解,本文讲解了变量-对象-引用.可变对象-不可变对象.拷贝等内容.   要说清楚Python中的深浅拷贝,需要 ...

  8. 利用python求解物理学中的双弹簧质能系统详解

    利用python求解物理学中的双弹簧质能系统详解 本文主要给大家介绍了关于利用python求解物理学中双弹簧质能系统的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧. 物理的 ...

  9. python中requests库使用方法详解

    目录 python中requests库使用方法详解 官方文档 什么是Requests 安装Requests库 基本的GET请求 带参数的GET请求 解析json 添加headers 基本POST请求 ...

随机推荐

  1. 并发07--线程池及Executor框架

    一.JAVA中的线程池 线程池的实现原理及流程如下图所示: 如上图所示,当一个线程提交到线程池时(execute()或submit()),先判断核心线程数(corePoolSize)是否已满,如果未满 ...

  2. RabbitMQ(dotnet基本使用

    前言 RabbitMQ环境环境搭建及基本配置,在此不讨论.网上一大堆. NET环境下,Rabbit库可以在官网或NUGET上查找得到. 生产者 static void Main(string[] ar ...

  3. gulp之demo

    1.安装gulp cnpm install -g gulp; 2.然后还需要在当前目录安装gulp,具体不详,只知道安装了之后会在当前目录下的node_modules下多一个gulp文件夹 cnpm ...

  4. redis基础02-redis的5种对象数据类型

    表格引用地址:http://www.cnblogs.com/xrq730/p/8944539.html 参考书籍:<Redis设计与实现>,<Redis运维与开发> 1.对象 ...

  5. SQL基础随记2 视图 存储过程

    SQL基础随记2 视图 存储过程   View CREATE/ALTER/DROP VIEW ViewName as SELECT(...) 可以在视图的基础上继续创建视图,即,将之前创建的视图当做表 ...

  6. 「期望」「洛谷P1297」单选错位

    题目 题目描述 gx和lc去参加noip初赛,其中有一种题型叫单项选择题,顾名思义,只有一个选项是正确答案.试卷上共有n道单选题,第i道单选题有ai个选项,这ai个选项编号是1,2,3,-,ai,每个 ...

  7. JAVA基础笔记10-11-12-13-14

    十.今日内容介绍 1.继承 2.抽象类 3.综合案例---员工类系列定义 01继承的概述 *A:继承的概念 *a:继承描述的是事物之间的所属关系,通过继承可以使多种事物之间形成一种关系体系 *b:在J ...

  8. MYSQL 之 JDBC(二): 数据库连接(二)通过DriverManager获取数据库连接

    通过DriverManager获取数据库连接 修改一下配置文件 driver=com.mysql.cj.jdbc.Driver jdbcUrl=jdbc:mysql://localhost:3306/ ...

  9. python 装饰器(三):装饰器实例(一)

    示例 7-15 定义了一个装饰器,它会在每次调用被装饰的函数时计时,然后把经过的时间.传入的参数和调用的结果打印出来.示例 7-15 一个简单的装饰器,输出函数的运行时间 import time de ...

  10. Python之爬虫(二十) Scrapy爬取所有知乎用户信息(上)

    爬取的思路 首先我们应该找到一个账号,这个账号被关注的人和关注的人都相对比较多的,就是下图中金字塔顶端的人,然后通过爬取这个账号的信息后,再爬取他关注的人和被关注的人的账号信息,然后爬取被关注人的账号 ...