grpc python

2023-04-23  本文已影响0人  hehehehe

./pip3 install grpcio grpcio-tools protobuf -i http://mirrors.aliyun.com/pypi/simple --trusted-host mirrors.aliyun.com

proto

// 指定版本
syntax="proto3";
// 包
package user;

// 创建service
service User {
    // user method
    rpc AddUser(UserRequest) returns (UserResponse) {}
    rpc GetUser(GetUserRequest) returns (GetUserResponse) {}
}

// 请求参数消息体 1、2 是指参数的个数顺序
message UserRequest {
    string username = 1;
    int32 age = 2;
}

// 返回参数消息体
message UserResponse {
    string err = 1;
}

// 请求参数消息体
message GetUserRequest {
    string username = 1;
}

// 返回参数消息体
message GetUserResponse {
    string username = 1;
    int32 age = 2;
}

python3 -m grpc_tools.protoc -I=. --python_out=. --grpc_python_out=. user.proto

server

# server.py
import time

import grpc
from concurrent import futures

import user_pb2, user_pb2_grpc
from user import UserServicer


def main():
    # futures.ThreadPoolExecutor(max_workers=10) 指定最大线程数,不指定默认是 cpu个数 x 5
    """
        if max_workers is None:
        # Use this number because ThreadPoolExecutor is often
        # used to overlap I/O instead of CPU work.
        max_workers = (os.cpu_count() or 1) * 5
    """
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    # 注册User Service
    user_server = UserServicer()
    user_pb2_grpc.add_UserServicer_to_server(user_server, server)
    # 启动服务
    server.add_insecure_port("127.0.0.1:8000")
    server.start()

    try:
        print('start rpc service')
        while True:
            time.sleep(60 * 60)
    except:
        server.stop(0)


if __name__ == '__main__':
    main()

client

# client.py
import grpc

from proto import user_pb2_grpc, user_pb2


def main():
    # 连接RPC 服务器
    channel = grpc.insecure_channel("localhost:8000")
    # 创建 Stub
    user_cli = user_pb2_grpc.UserStub(channel)
    # 调用 AddUser
    value = user_cli.AddUser(user_pb2.UserRequest(username='danni', age=20))
    print(value)


if __name__ == '__main__':
    main()
# user.py
import user_pb2, user_pb2_grpc


class UserServicer(user_pb2_grpc.UserServicer):
    def AddUser(self, request, context):
        print(request.username, request.age)
        # 具体的业务逻辑
        return user_pb2.UserResponse(err='ok')

    def GetUser(self, request, context):
        print(request.username)
        # 具体的业务逻辑
        return user_pb2.GetUserResponse(username='danni', age=12)

上一篇下一篇

猜你喜欢

热点阅读