GRPC 学习记录

GRPC 安装

安装 grpcio、grpcio-tools、protobuf、

pip install grpcio -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install grpcio-tools -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install protobuf -i https://pypi.tuna.tsinghua.edu.cn/simple

常用类型

在这里插入图片描述

proto 文件

// 选择 proto3
syntax = "proto3";

// 名字
package test;

// 服务{函数}
service Bilili {
    rpc Hello(HelloReq) returns (HelloReply) {}  // 双向非流
    // rpc Hello(stream HelloReq) returns (stream HelloReply) {}  // stream 保持链接
}

// 双向非流 参数定义
// 输入函数
message HelloReq {
    string name = 1;
    int32 age = 2;
    repeated string data = 3;
    map<string, demo1> number = 4;
}

message demo1 {
    string n1 = 1;
    int64 n2 = 2;
    bool n3 = 3;
}


// 返回函数
message HelloReply {
    string result = 1;
}

proto 文件 转换为 python 命令

我的文件名:test.proto

python -m grpc_tools.protoc -I. --python_out=. --pyi_out=. --grpc_python_out=. test.proto

客户端

# client.py
import grpc
import test_pb2_grpc as pb2_grpc
import test_pb2 as pb2


def run():
    # 绑定地址
    conn = grpc.insecure_channel('127.0.0.1:5001')
    # 绑定对应服务
    client = pb2_grpc.BililiStub(channel=conn)
    # 绑定服务对应的函数
    response = client.Hello(pb2.HelloReq(
        name='SB',
        age=33,
        data=['1', '2', '3'],
        number={'sb': pb2.demo1(n1='q', n2=33, n3=True)}
    ), )

    print(response.result)


if __name__ == '__main__':
    run()

服务端

# service.py
import time
import grpc
import test_pb2 as pb2
import test_pb2_grpc as pb2_grpc
from concurrent import futures


class Bili(pb2_grpc.BililiServicer):
    def Hello(self, request, context):
        name = request.name
        age = request.age
        data = request.data
        map_1 = request.number

        result = f'姓名: {name}, 年龄: {age} 数组:{data} 字典:{map_1}'
        return pb2.HelloReply(result=result)


def run():
    # 服务
    grpc_server = grpc.server(
        # 设置了4个进程
        futures.ThreadPoolExecutor(max_workers=4),
    )
    # 注册服务
    pb2_grpc.add_BililiServicer_to_server(Bili(), grpc_server)
    # 绑定 地址
    grpc_server.add_insecure_port('0.0.0.0:5001')
    print('server start..')
    grpc_server.start()

    try:
        while True:
            time.sleep(3600)
    # 按Ctrl + c
    except KeyboardInterrupt:
        # 安全退出
        grpc_server.stop(0)


if __name__ == '__main__':
    run()

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

默执_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值