python模塊之 - grpc


# gRPC 的安裝:
# $ pip install grpcio
# 安裝 ProtoBuf 相關的 python 依賴庫:
# $ pip install protobuf
# 安裝 python grpc 的 protobuf 編譯工具:
# $ pip install grpcio-tools

python -m grpc_tools.protoc --python_out=. --grpc_python_out=. *.proto
syntax = "proto3";

package proto;

//
service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
  string name = 2;
}

message HelloReply {
  string message = 1;
}
proto

 

golang grpc默認50001端口

 

 client
import grpc
import user_pb2
import user_pb2_grpc


def run():
    # 請求的ip和端口地址
    with grpc.insecure_channel('localhost:50001') as channel:
        stub = user_pb2_grpc.GreeterStub(channel)
        response = stub.SayHello(user_pb2.HelloRequest(name="asdasdasdasdasd"))
    print("Greeter client received: " + response.message)


if __name__ == '__main__':
    run()
server
from concurrent import futures
import time
import grpc

import user_pb2
import user_pb2_grpc

_ONE_DAY_IN_SECONDS = 60 * 60 * 24


# Greeter:服務名;SayHello:方法名
class Greeter(user_pb2_grpc.GreeterServicer):

    def SayHello(self, request, context):
        # 請求內容在request中,取數據:request.name
        return user_pb2.HelloReply(message='Hello, %s!' % request.name)


def serve():
    # max_workers:最大連接數
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    user_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    # 服務啟動的ip和端口
    server.add_insecure_port('[::]:50001')
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)


if __name__ == '__main__':
    serve()

可以和 golang 服務端,客戶端  隨意配合

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM