Grpc在Python下的小小小操作

本来已经快写完了,。手贱关了网页,只能重头开始写哇!
Grpc是Google一个开源的基于http/2的一个rpc(远程过程调用)框架,同时使用 protocol buffers (类似json)来作为序列化和反序列化,支持多种语言。
本文主要内容为
* 在一个 .proto 文件内定义服务。
*用 protocol buffer 编译器生成服务器和客户端代码。
*使用 gRPC 的 Python API 来实现一个简单的客户端和服务器。

首先我们要在python使用grpc,先安装pip,接下来开始安装必要的包和库

安装gRPC:
pip install grpc

安装 ProtocolBuffers 相关的 python 依赖库:
pip install protobuf

安装 python grpc 的 protobuf 编译工具:
pip install grpcio-tools
然后可以开始定义一个服务(创建客户端和服务端方法等)
服务文件格式为 xx.proto
下面文件名为 hello.proto
message为参数和返回值格式 rpc为方法 syntax设置当前版本

syntax = "proto3";
service Action{
    rpc hihi(ActionRequest) returns (ActionResponse){}
}


message ActionRequest {
    string action = 1;
}

message ActionResponse{
    string message = 1;
}

下一段长长的指令来编译出两个py文件
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. ./hello.proto
编译生成 hello_pd2.py和hello_pd2_grpc.py两个文件

客户端和服务端通过继承 编译产生的两个文件的基类来完成

首先是服务端的构建


from concurrent import futures
import time

import grpc

import helloworld_pb2
import helloworld_pb2_grpc

_ONE_DAY_IN_SECONDS = 60 * 60 * 24

#继承基类
class Greeter(helloworld_pb2_grpc.GreeterServicer):

  def SayHello(self, request, context):
    return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)


def serve():
#定义服务器并设置最大连接数,corcurrent.futures是一个并发库,类似于线程池的概念
  server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
#添加一个服务
  helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
#设置服务器监听端口号
  server.add_insecure_port('[::]:50051')
  server.start()
  try:
    while True:
      time.sleep(_ONE_DAY_IN_SECONDS)
  except KeyboardInterrupt:
    server.stop(0)

if __name__ == '__main__':
  serve()

以下是客户端代码

from __future__ import print_function

import grpc

import helloworld_pb2
import helloworld_pb2_grpc


def run():
 #创建客户端与服务端的连接
  channel = grpc.insecure_channel('IP:PORT')
  stub = helloworld_pb2_grpc.GreeterStub(channel)
 #直接发起请求 (请求参数根据格式来)
  response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
  print("Greeter client received: " + response.message)


if __name__ == '__main__':
  run()

grpc简例完成!

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值