gRPC与RPC的差异

打印 上一主题 下一主题

主题 1503|帖子 1503|积分 4509

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
在微服务架构日益流行的今天,远程过程调用(RPC)技术成为毗连各个服务的紧张桥梁。本文将详细比较传统RPC与谷歌开辟的gRPC框架,通过具体示例展示它们在哀求处置惩罚、数据格式、性能等方面的差异。
根本概念回顾

RPC (远程过程调用) 是一种允许步伐调用另一台计算机上服务的通信协议,是分布式计算的底子。
gRPC 是Google开辟的高性能、开源RPC框架,基于HTTP/2协议并使用Protocol Buffers作为接口定义语言。
哀求处置惩罚方式对比

传统RPC(以XML-RPC为例)

XML-RPC使用简单的HTTP POST哀求,每次哀求都需要创建新的TCP毗连。
示例代码(XML-RPC客户端调用):
  1. import xmlrpc.client
  2. # 创建客户端
  3. server = xmlrpc.client.ServerProxy("http://localhost:8000")
  4. # 同步调用远程方法
  5. result = server.get_user_info(user_id=123)
  6. print(f"用户信息: {result}")
  7. # 另一个请求需要重新建立连接
  8. another_result = server.get_product_details(product_id=456)
复制代码
缺点:

  • 每个哀求都是独立的HTTP毗连
  • 不支持流式数据
  • 毗连复用本领弱
gRPC哀求处置惩罚

gRPC基于HTTP/2,支持多路复用和双向流。
示例代码(使用gRPC客户端):
  1. import grpc
  2. import user_service_pb2
  3. import user_service_pb2_grpc
  4. # 创建channel连接
  5. with grpc.insecure_channel('localhost:50051') as channel:
  6.     # 创建stub
  7.     stub = user_service_pb2_grpc.UserServiceStub(channel)
  8.    
  9.     # 单次请求-响应
  10.     request = user_service_pb2.GetUserRequest(user_id=123)
  11.     response = stub.GetUser(request)
  12.     print(f"用户信息: {response.name}, {response.email}")
  13.    
  14.     # 服务器流式RPC
  15.     for product in stub.ListProducts(user_service_pb2.ListProductsRequest(category="electronics")):
  16.         print(f"产品: {product.name}, 价格: {product.price}")
  17.    
  18.     # 客户端流式RPC
  19.     def generate_logs():
  20.         logs = [
  21.             user_service_pb2.LogEntry(timestamp="2023-01-01", message="登录"),
  22.             user_service_pb2.LogEntry(timestamp="2023-01-02", message="购买商品"),
  23.             user_service_pb2.LogEntry(timestamp="2023-01-03", message="登出")
  24.         ]
  25.         for log in logs:
  26.             yield log
  27.    
  28.     summary = stub.ProcessLogs(generate_logs())
  29.     print(f"日志处理结果: {summary.success}")
  30.    
  31.     # 双向流式RPC
  32.     responses = stub.Chat(generate_messages())
  33.     for response in responses:
  34.         print(f"收到消息: {response.text}")
复制代码
长处:

  • 一个毗连可处置惩罚多个并发哀求(多路复用)
  • 支持四种调用模式:

    • 单次哀求-响应
    • 服务器流式RPC(一次哀求,多次响应)
    • 客户端流式RPC(多次哀求,一次响应)
    • 双向流式RPC(多次哀求,多次响应)

  • 淘汰了毗连创建的开销
数据格式对比

传统RPC的数据格式(以JSON-RPC为例)

JSON-RPC哀求示例:
  1. {
  2.   "jsonrpc": "2.0",
  3.   "method": "getUserProfile",
  4.   "params": {
  5.     "userId": 12345,
  6.     "includeDetails": true
  7.   },
  8.   "id": 1
  9. }
复制代码
JSON-RPC响应示例:
  1. {
  2.   "jsonrpc": "2.0",
  3.   "result": {
  4.     "userId": 12345,
  5.     "username": "johndoe",
  6.     "email": "john@example.com",
  7.     "registrationDate": "2021-06-15",
  8.     "lastLogin": "2023-01-20T14:30:15Z",
  9.     "preferences": {
  10.       "theme": "dark",
  11.       "notifications": true
  12.     }
  13.   },
  14.   "id": 1
  15. }
复制代码
特点:

  • 人类可读的文本格式
  • 结构机动,没有严格的模式约束
  • 序列化/反序列化开销较大
  • 数据体积较大
gRPC的Protocol Buffers格式

Proto文件定义示例:
  1. syntax = "proto3";
  2. package user;
  3. service UserService {
  4.   rpc GetUserProfile(UserRequest) returns (UserProfile) {}
  5. }
  6. message UserRequest {
  7.   int32 user_id = 1;
  8.   bool include_details = 2;
  9. }
  10. message UserProfile {
  11.   int32 user_id = 1;
  12.   string username = 2;
  13.   string email = 3;
  14.   string registration_date = 4;
  15.   string last_login = 5;
  16.   UserPreferences preferences = 6;
  17. }
  18. message UserPreferences {
  19.   string theme = 1;
  20.   bool notifications = 2;
  21. }
复制代码
特点:

  • 紧凑的二进制格式
  • 结构由.proto文件严格定义
  • 高效的序列化/反序列化
  • 数据体积小,传输服从高
  • 自动天生代码,类型安全
性能对比: 对于同样的用户数据,JSON格式大概需要约200字节,而Protocol Buffers大概只需要约50-100字节。序列化速率通常比JSON快2-10倍。
性能对比示例

场景:获取1000个用户信息

传统RPC(基于HTTP/1.1和JSON):
  1. import requests
  2. import json
  3. import time
  4. def get_users_rest():
  5.     start_time = time.time()
  6.     users = []
  7.    
  8.     # 发送1000个独立的HTTP请求
  9.     for i in range(1000):
  10.         response = requests.get(f"http://api.example.com/users/{i}")
  11.         users.append(response.json())
  12.    
  13.     end_time = time.time()
  14.     return len(users), end_time - start_time
  15. count, duration = get_users_rest()
  16. print(f"REST API: 获取了{count}个用户,耗时{duration:.2f}秒")
  17. # 示例输出: REST API: 获取了1000个用户,耗时10.45秒
复制代码
使用gRPC:
  1. import grpc
  2. import user_pb2
  3. import user_pb2_grpc
  4. import time
  5. def get_users_grpc():
  6.     start_time = time.time()
  7.    
  8.     with grpc.insecure_channel('api.example.com:50051') as channel:
  9.         stub = user_pb2_grpc.UserServiceStub(channel)
  10.         
  11.         # 使用流式RPC一次请求获取所有用户
  12.         request = user_pb2.GetUsersRequest(limit=1000)
  13.         users = list(stub.GetUsers(request))
  14.    
  15.     end_time = time.time()
  16.     return len(users), end_time - start_time
  17. count, duration = get_users_grpc()
  18. print(f"gRPC: 获取了{count}个用户,耗时{duration:.2f}秒")
  19. # 示例输出: gRPC: 获取了1000个用户,耗时1.23秒
复制代码
上述性能差异主要源于:

  • gRPC使用HTTP/2多路复用,淘汰毗连创建开销
  • Protocol Buffers的高效二进制序列化
  • 流式处置惩罚本领,淘汰了哀求次数
服务定义方式对比

REST API(传统方式)

通常使用OpenAPI/Swagger来描述:
  1. openapi: 3.0.0
  2. info:
  3.   title: User Service API
  4.   version: 1.0.0
  5. paths:
  6.   /users/{userId}:
  7.     get:
  8.       summary: 获取用户信息
  9.       parameters:
  10.         - name: userId
  11.           in: path
  12.           required: true
  13.           schema:
  14.             type: integer
  15.       responses:
  16.         '200':
  17.           description: 用户信息
  18.           content:
  19.             application/json:
  20.               schema:
  21.                 type: object
  22.                 properties:
  23.                   userId:
  24.                     type: integer
  25.                   username:
  26.                     type: string
  27.                   email:
  28.                     type: string
复制代码
特点:

  • 使用HTTP动词表示操纵
  • 资源中央的计划
  • 文档通常与实现分离
  • 客户端代码通常需要手动实现
gRPC服务定义

使用Protocol Buffers IDL(接口定义语言):
  1. syntax = "proto3";
  2. package ecommerce;
  3. service ProductService {
  4.   // 获取单个产品
  5.   rpc GetProduct(GetProductRequest) returns (Product) {}
  6.   
  7.   // 搜索产品
  8.   rpc SearchProducts(SearchRequest) returns (stream Product) {}
  9.   
  10.   // 批量上传产品
  11.   rpc UploadProducts(stream Product) returns (UploadSummary) {}
  12.   
  13.   // 实时价格更新
  14.   rpc PriceWatch(stream PriceRequest) returns (stream PriceUpdate) {}
  15. }
  16. message GetProductRequest {
  17.   string product_id = 1;
  18. }
  19. message SearchRequest {
  20.   string query = 1;
  21.   int32 result_per_page = 2;
  22.   int32 page_number = 3;
  23. }
  24. message Product {
  25.   string id = 1;
  26.   string name = 2;
  27.   string description = 3;
  28.   double price = 4;
  29.   repeated string categories = 5;
  30.   ProductInventory inventory = 6;
  31. }
  32. message ProductInventory {
  33.   int32 quantity = 1;
  34.   string warehouse_id = 2;
  35. }
  36. message UploadSummary {
  37.   int32 success_count = 1;
  38.   int32 failure_count = 2;
  39. }
  40. message PriceRequest {
  41.   string product_id = 1;
  42. }
  43. message PriceUpdate {
  44.   string product_id = 1;
  45.   double new_price = 2;
  46.   string update_time = 3;
  47. }
复制代码
特点:

  • 明确的方法定义
  • 严格的类型查抄
  • 可以自动天生客户端和服务端代码
  • 接口、数据类型和实现精密集成
错误处置惩罚对比

REST API错误处置惩罚

示例HTTP错误响应:
  1. {
  2.   "error": {
  3.     "code": 404,
  4.     "message": "User not found",
  5.     "details": "The user with ID 12345 does not exist in our system"
  6.   }
  7. }
复制代码

  • 使用HTTP状态码表示错误类型
  • 错误格式不标准,各服务大概不同
  • 需要手动解析错误信息
gRPC错误处置惩罚

定义错误类型:
  1. message ErrorDetail {
  2.   string field = 1;
  3.   string description = 2;
  4. }
  5. message ErrorResponse {
  6.   int32 code = 1;
  7.   string message = 2;
  8.   repeated ErrorDetail details = 3;
  9. }
复制代码
服务端实现:
  1. def GetUser(self, request, context):
  2.     user = database.find_user(request.user_id)
  3.     if not user:
  4.         context.set_code(grpc.StatusCode.NOT_FOUND)
  5.         context.set_details(f"User {request.user_id} not found")
  6.         return user_pb2.UserProfile()  # 返回空对象
  7.     return user
复制代码
客户端处置惩罚:
  1. try:
  2.     response = stub.GetUser(request)
  3.     print(f"用户信息: {response}")
  4. except grpc.RpcError as e:
  5.     status_code = e.code()
  6.     if status_code == grpc.StatusCode.NOT_FOUND:
  7.         print(f"错误: 用户不存在 - {e.details()}")
  8.     else:
  9.         print(f"RPC错误: {status_code} - {e.details()}")
复制代码
特点:

  • 标准化的错误码和错误处置惩罚机制
  • 内置的状态码体系
  • 客户端可以通过异常机制处置惩罚错误
  • 更加类型安全
实际应用场景选择指南

选择传统RPC(REST、SOAP等)的场景:


  • 前端直接调用API场景

    • 网页前端需要直接调用后端API
    • 需要良好的欣赏器兼容性
    • 示例:电商网站的商品欣赏页面

  • 对接第三方开放平台

    • 大多数公开API仍使用REST风格
    • 示例:接入支付宝、微信支付等第三方服务

  • 简单的集成需求
    1. // 前端调用REST API示例
    2. async function getUserProfile(userId) {
    3.   const response = await fetch(`/api/users/${userId}`);
    4.   if (!response.ok) {
    5.     throw new Error('获取用户信息失败');
    6.   }
    7.   return response.json();
    8. }
    复制代码
选择gRPC的场景:


  • 微服务内部通信

    • 服务之间需要高效通信
    • 有明确定义的接口契约
    • 示例:电商平台的订单服务调用库存服务、支付服务

  • 实时数据流应用
    1. // Go语言实现股票价格实时推送服务
    2. func (s *StockServer) PriceStream(request *pb.StockRequest, stream pb.StockService_PriceStreamServer) error {
    3.   symbol := request.Symbol
    4.   for {
    5.     price := getLatestPrice(symbol)
    6.     if err := stream.Send(&pb.StockPrice{
    7.       Symbol: symbol,
    8.       Price: price,
    9.       Timestamp: time.Now().Unix(),
    10.     }); err != nil {
    11.       return err
    12.     }
    13.     time.Sleep(1 * time.Second)
    14.   }
    15. }
    复制代码
  • 移动应用与后端通信

    • 移动网络环境下对性能和数据量敏感
    • 需要强类型保障API稳定性
    • 示例:即时通讯应用

  • 多语言环境

    • 不同语言开辟的微服务需要相互调用
    • 示例:Python数据处置惩罚服务与Go实现的API网关通信

总结

特性传统RPCgRPC传输协议多样(HTTP/1.1, TCP)HTTP/2数据格式XML, JSON等Protocol Buffers代码天生通常不自动天生自动天生多语言客户端/服务端流处置惩罚不支持或有限支持完全支持四种流模式毗连模型通常是短毗连长毗连+多路复用类型安全弱类型或手动校验强类型实用场景简单集成、欣赏器访问微服务、高性能场景、多语言环境gRPC带来了显著的性能提升和开辟服从的提高,但也需要更复杂的底子设施支持。在选择技术栈时,应根据实际需求衡量利弊,选择最适合的办理方案。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

李优秀

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表