LearnLog(gRPC)

本文介绍了gRPC,一个高性能的RPC框架,详细讲解了如何编写.proto文件、使用Python生成服务端和客户端代码,并展示了服务端和客户端的交互过程。
摘要由CSDN通过智能技术生成

grpc介绍

“gRPC是一个google开发的高性能、开源、通用的远程过程调用(RPC)框架,可以在任何环境中运行。它旨在通过对负载平衡、跟踪、健康检查和身份验证的可插拔支持,有效地连接数据中心内和跨数据中心的服务。gRPC基于HTTP/2协议,并使用Protocol Buffers作为其接口定义语言(IDL)。它广泛用于构建分布式系统和微服务,因为它允许在用不同编程语言编写的不同服务之间轻松通信

1. 编写.proto文件

//使用软件版本
syntax = "proto3";

//生成两个py文件的前缀名
package algorithm;


service AlgoCaller {
//绑定请求响应方法
  rpc Call (CallRequest) returns (CallReply) {}
}

//定义客户端请求字段
message CallRequest {
  string funcname = 1;
  int32 num =2;

}

//定义服务端响应字段
message CallReply {
  string ret = 1;
}

2.使用命令行生成两个py

 python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. algorithm.proto

这里有一个坑,grpc_python_out这个参数传的地址是不包含.proto文件的。.proto文件单独放到最后就行了,其他参数后面的点表示当前路径。

3.编写服务端

import grpc
from concurrent import futures
import algorithm_pb2
import algorithm_pb2_grpc

funcList=[]

def API(func):
    if not func.__name__ in funcList:
        funcList.append(func.__name__)
    return func

#根据传递的函数名调用本地函数
@API
def erode(i):
    return str(i ** 2)


class AlgoServicer(algorithm_pb2_grpc.AlgoCallerServicer):

    def Call(self, request, context):
        ret = eval(f"{request.funcname}({request.num})") if request.funcname in funcList else f"no api name {request.funcname}"
        return algorithm_pb2.CallReply(ret=ret)

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    algorithm_pb2_grpc.add_AlgoCallerServicer_to_server(AlgoServicer(), server)
    server.add_insecure_port("localhost:50051")
    server.start()
    print("Server started on port 50051")
    server.wait_for_termination()


if __name__=="__main__":
    serve()

4.编写客户端

import grpc
import algorithm_pb2
import algorithm_pb2_grpc
import time


def connect():
    channel = grpc.insecure_channel("localhost:50051")
    stub = algorithm_pb2_grpc.AlgoCallerStub(channel)
    i = 0
    while True:
        response = stub.Call(algorithm_pb2.CallRequest(funcname="erode", num=i))
        print(f"Received: {response.ret}")
        time.sleep(1)
        i += 1


if __name__ == '__main__':
    connect()

5.测试

先运行服务端程序,再运行客户端程序即可。客户端传int消息到服务端,服务端收到int然后进行平方运算返回到客户端打印

#服务端log
add api erode
Server started on port 50051
...


#客户端log
Received: 0
Received: 1
Received: 4
Received: 9
Received: 16
Received: 25
Received: 36
....
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值