RPC 框架 应用

RPC

RPC(Remote Procedure Call)服务,也即远程过程调用,在互联网企业技术架构中占据了举足轻重的地位,尤其在当下微服务化逐步成为大中型分布式系统架构的主流背景下,RPC 更扮演了重要角色。

Google 开源了 gRPC,Facebook 开源了 Thrift,Twitter 开源了 Finagle,百度开源了 bRPC,腾讯开源了 Tars,阿里开源了 Dubbo 和 HSF,新浪开源了 Motan 等,一线互联网大厂们纷纷亮出自己研制的 RPC 框架武器,在解决分布式高并发业务问题的同时,也向外界展示自己的技术实力。

互联网公司百花齐放,貌似高深复杂的 RPC 框架解决了哪些业务难题?

gRPC 简介:

gRPC 是一款高性能、开源的 RPC 框架,产自 Google,基于 ProtoBuf 序列化协议进行开发,支持多种语言(Golang、Python、Java等),本篇只介绍 Python 的 gRPC 使用。因为 gRPC 对 HTTP/2 协议的支持使其在 Android、IOS 等客户端后端服务的开发领域具有良好的前景。gRPC 提供了一种简单的方法来定义服务,同时客户端可以充分利用 HTTP/2 stream 的特性,从而有助于节省带宽、降低 TCP 的连接次数、节省CPU的使用等。

安装:

gRPC 的安装:

$ pip install grpcio

安装 ProtoBuf 相关的 python 依赖库

$ pip install protobuf

安装 python grpc 的 protobuf 编译工具:

pip install grpcio-tools

实践:

下面我们使用 gRPC 定义一个接口,该接口实现对传入的数据进行大写的格式化处理

创建项目 python demo 工程

client目录下的 main.py 实现了客户端用于发送数据并打印接收到 server 端处理后的数据
  1. server 目录下的 main.py 实现了 server 端用于接收客户端发送的数据,并对数据进行大写处理后返回给客户端
  2. example 包用于编写 proto 文件并生成 data 接口

定义 gRPC 接口:

syntax = "proto3";
package example;
service FormatData {
  rpc DoFormat(Data) returns (Data){}
}
message Data {
  string text = 1;
}

编译 protobuf

python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. ./data.proto 

#在 example 目录中执行编译,会生成:data_pb2.py 与 data_pb2_grpc.py

实现 server 端:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
import grpc
import time
from concurrent import futures
from example import data_pb2, data_pb2_grpc

_ONE_DAY_IN_SECONDS = 60 * 60 * 24
_HOST = 'localhost'
_PORT = '8080'

class FormatData(data_pb2_grpc.FormatDataServicer):
    def DoFormat(self, request, context):
        str = request.text
        return data_pb2.Data(text=str.upper())

def serve():
    grpcServer = grpc.server(futures.ThreadPoolExecutor(max_workers=4))
    data_pb2_grpc.add_FormatDataServicer_to_server(FormatData(), grpcServer)
    grpcServer.add_insecure_port(_HOST + ':' + _PORT)
    grpcServer.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        grpcServer.stop(0)

if __name__ == '__main__':
    serve()

实现 client 端:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
import grpc
from example import data_pb2, data_pb2_grpc

_HOST = 'localhost'
_PORT = '8080'

def run():
    conn = grpc.insecure_channel(_HOST + ':' + _PORT)
    client = data_pb2_grpc.FormatDataStub(channel=conn)
    response = client.DoFormat(data_pb2.Data(text='hello,world!'))
    print("received: " + response.text)

if __name__ == '__main__':
    run()

执行验证结果:

先启动 server,之后再执行 client

client 侧控制台如果打印的结果为:“received: HELLO,WORLD!” ,证明 gRPC 接口定义成功

原文地址:https://www.cnblogs.com/jiangchunsheng/p/10697148.html