微服务-grpc

grpc

简介

  • 概述

gRPC 是一个高性能、开源和通用的 RPC 框架,面向移动和 HTTP/2 设计。目前提供 C、Java 和 Go 语言版本,分别是:grpc, grpc-java, grpc-go. 其中 C 版本支持 C, C++, Node.js, Python, Ruby, Objective-C, PHPC# 支持.

  • 官方链接:

​ 开源中国组织翻译的《gRPC 官方文档中文版》:http://doc.oschina.net/grpc

  • 特点:

gRPC 基于 HTTP/2 标准设计,带来诸如双向流、流控、头部压缩、单 TCP 连接上的多复用请求等特。这些特性使得其在移动设备上表现更好,更省电和节省空间占用。

安装

  • python
    • pip install grpcio grpcio-tools protobuf

创建proto协议文件

  • touch hello_test.proto

  • syntax = "proto3";
    
    package test;
    
    // 定义服务
    service Bilibili {
        rpc Helloserver(HelloServerReq) returns (HelloServerResp){}
    }
    // 定义请求结构体
    message HelloServerReq {
        string name = 1;
        int32 age = 2;
    }
    
    // 定义返回结构体
    message HelloServerResp {
        string result = 1;
    }
    
    
  • 生成所需文件

    • python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. hello_bilibili.proto

编写服务

  • touch service.py

    # coding:utf-8
    
    import time
    
    import grpc
    import hello_bilibili_pb2 as pb2
    import hello_bilibili_pb2_grpc as pb2_grpc
    # 创建线程
    from concurrent import futures
    
    class Bilibili(pb2_grpc.BilibiliServicer):
        def Helloserver(self,request,context):
            name = request.name
            age = request.age
            result = f"my name is {name}. i am {age} years old"
            return pb2.HelloServerResp(result=result)
    
    def run():
        grpc_server = grpc.server(
            # 设置线程最大工作数量
            futures.ThreadPoolExecutor(max_workers=4)
        )
        # 注册服务
        pb2_grpc.add_BilibiliServicer_to_server(Bilibili(),grpc_server)
    
        print("server will start at 0.0.0.0:5000")
        # 绑定 ip+port
        grpc_server.add_insecure_port("0.0.0.0:5000")
        grpc_server.start()
    
        try:
            while 1:
                time.sleep(3600)
    
        except KeyboardInterrupt:
            grpc_server.stop(0)
    
    if __name__ == "__main__":
        run()
    
  • 创建客户端

    • touch client.py

    • # coding:utf-8
      
      import grpc
      import hello_bilibili_pb2 as pb2
      import hello_bilibili_pb2_grpc as pb2_grpc
      
      def run():
          # 绑定通道
          conn = grpc.insecure_channel("localhost:5000")
          client = pb2_grpc.BilibiliStub(channel=conn)
          response = client.Helloserver(pb2.HelloServerReq(
              name= 'tangjinman',
              age = 20
          ))
          print(response.result)
      
      if __name__ == "__main__":
          run()
      
原文地址:https://www.cnblogs.com/jmtang/p/14227038.html