Protocol Buffers简明教程

本文介绍Protocol Buffers这一高效、简洁的序列化协议。它是Google开源的一种语言和平台无关的数据序列化框架,支持多种语言,具备良好的兼容性和高性能。文中还探讨了其历史背景及实际应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  随着微服务架构的流行,RPC框架渐渐地成为服务框架的一个重要部分。

  在很多RPC的设计中,都采用了高性能的编解码技术,Protocol Buffers就属于其中的佼佼者。

  Protocol Buffers是Google开源的一个语言无关、平台无关的通信协议,其小巧、高效和友好的兼容性设计,使其被广泛使用。

概述

protobuf是什么?

Protocol buffers are Google’s language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler. You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages.
  • Google良心企业出厂的;
  • 是一种序列化对象框架(或者说是编解码框架),其他功能相似的有Java自带的序列化、Facebook的Thrift和JBoss Marshalling等;
  • 通过proto文件定义结构化数据,其他功能相似的比如XML、JSON等;
  • 自带代码生成器,支持多种语言;

核心特点

  • 语言无关、平台无关
  • 简洁
  • 高性能
  • 良好的兼容性

 

为什么叫“Protocol Buffers”?

官方如是说:

The name originates from the early days of the format, before we had the protocol buffer compiler to generate classes for us. At the time, there was a class called ProtocolBuffer which actually acted as a buffer for an individual method. Users would add tag/value pairs to this buffer individually by calling methods like AddValue(tag, value). The raw bytes were stored in a buffer which could then be written out once the message had been constructed.

Since that time, the “buffers” part of the name has lost its meaning, but it is still the name we use. Today, people usually use the term “protocol message” to refer to a message in an abstract sense, “protocol buffer” to refer to a serialized copy of a message, and “protocol message object” to refer to an in-memory object representing the parsed message.

 

“变态的”性能表现

有位网友曾经做过各种通用序列化协议技术的对比,我这里直接拿来给大家感受一下:

序列化响应时间对比


序列化bytes对比

具体的数字

快速开始

以下示例源码已上传至github:ginobefun/learning_projects

新建一个maven项目并添加依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ginobefunny.learning</groupId>
    <artifactId>leanring-protobuf</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java</artifactId>
            <version>3.2.0</version>
        </dependency>
    </dependencies>
</project>

 

 

 

 

转载至:https://zhuanlan.zhihu.com/p/25174418

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值