1. 程式人生 > 實用技巧 >微服務-grpc

微服務-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()