1. 程式人生 > >Google Protocol Buffer入門

Google Protocol Buffer入門

解釋 -- rate plugin gcc 入門 新增 查找 abs

簡介

Google Protocol Buffer( 簡稱 Protobuf) 是 Google 公司內部的混合語言數據標準,目前已經正在使用的有超過 48,162 種報文格式定義和超過 12,183 個 .proto 文件。他們用於 RPC 系統和持續數據存儲系統。

Protocol Buffers 是一種輕便高效的結構化數據存儲格式,可以用於結構化數據串行化,或者說序列化。它很適合做數據存儲或 RPC 數據交換格式。可用於通訊協議、數據存儲等領域的語言無關、平臺無關、可擴展的序列化結構數據格式。目前提供了 C++、Java、Python 三種語言的 API。

如果你在開發中使用過常用的數據交換格式如xml、json,那麽protocol buffer也不是什麽神奇的東西了,它和xml、json類似,也可以作為開發中的一種數據交換格式,只不過相較xml和json,protocol buffer的優點更明顯,它更小、更快、更簡單。

windows下使用Protobuf

對比非C++用戶,可以直接下載官網預編譯好的protoc.exe(install the protocol compiler is to download a pre-built binary):
https://repo1.maven.org/maven2/com/google/protobuf/protoc/

Java中使用ProtocolBuffer

在Java中使用ProtocolBuffer的步驟大致分為下面這幾點:

  • (1)編寫.proto文件,定義消息類型

application.proto

syntax = "proto2";
package proto;
option java_package = "com.ziyun.bean.proto";
option java_outer_classname = "IpAddress";
message ip_address {
    optional string af = 1;
    optional string addr = 2;
}
  • (2)使用ProtocolBuffer的編譯器(protoc.exe),將.proto文件編譯成對應的java文件

    public class GenereteBeanUtil {
    
    /**
     * 通過執行cmd命令調用protoc.exe程序
     * 參考命令:protoc2.exe -I=./ --java_out=./ ./proto/access_point.proto
     *
     * @param absolutePath  exe程序絕對路徑
     * @param protoFileName proto文件名
     */
    public static void generateBean(String absolutePath, String protoFileName) {
        String[] cmd = {absolutePath + "protoc2.exe", "-I=" + absolutePath, "--java_out=" + absolutePath,
                absolutePath + "proto/" + protoFileName};
        try {
            Runtime.getRuntime().exec(cmd);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) throws IOException {
        File directory = new File("");
        String absolutePath = directory.getAbsolutePath();
    
        //proto文件路徑
        String protoPath = absolutePath + File.separator + "zy-libs" + File.separator + "zy-zeromq"
                + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator +
                "proto" + File.separator;
        String dirPath = absolutePath + File.separator + "zy-libs" + File.separator + "zy-zeromq" + File.separator +
                "src" + File.separator + "main" + File.separator + "java" + File.separator;
    
        File dir = new File(protoPath);
        File[] files = dir.listFiles();
        for (File file : files) {
            String fileName = file.getName();
            GenereteBeanUtil.generateBean(dirPath, fileName);
        }
    }
    }
  • (3)在Java代碼中使用上一步編譯好的java文件
    ```
    IpAddress.ip_address.Builder builder = IpAddress.ip_address.newBuilder();
    builder.setAddr("10.130.254.6");
    builder.setAf("af" + String.valueOf(i));
    IpAddress.ip_address ipAddress = builder.build();

publisher.send(ipAddress.toByteArray(), ZMQ.NOBLOCK);




## 語法
### 類型對比
![image](E:/image/prototype.png)

### package
.proto文件新增一個可選的package聲明符,用來防止不同的消息類型有命名沖突。包的聲明符會根據使用語言的不同影響生成的代碼。對於C++,產生的類會被包裝在C++的命名空間中。

### 枚舉(enum)

enum PhoneType //枚舉消息類型
{
MOBILE = 0; //proto3版本中,首成員必須為0,成員不應有相同的值
HOME = 1;
WORK = 2;
}


### 指定字段規則
所指定的消息字段修飾符必須是如下之一:
-   required:一個格式良好的消息一定要含有1個這種字段。表示該值是必須要設置的;
- optional:消息格式中該字段可以有0個或1個值(不超過1個)。
- repeated:在一個格式良好的消息中,這種字段可以重復任意多次(包括0次)。重復的值的順序會被保留。表示該值可以重復,相當於java中的List。
由於一些歷史原因,基本數值類型的repeated的字段並沒有被盡可能地高效編碼。在新的代碼中,用戶應該使用特殊選項[packed=true]來保證更高效的編碼。如:
repeated int32 samples = 4 [packed=true];



### import

import "myproject/other_protos.proto";

protocol編譯器就會在一系列目錄中查找需要被導入的文件,這些目錄通過protocol編譯器的命令行參數-I/–import_path指定。如果不提供參數,編譯器就在其調用目錄下查找。

### protoc命令參數
protoc2.exe -I=./ --java_out=./ ./proto/access_point.proto

$ protoc -I=./src --python_out=./out ./src/*.proto  //用protoc3試試

$ protoc -help
Usage: protoc [OPTION] PROTO_FILES
Parse PROTO_FILES and generate output based on the options given:
-IPATH, --proto_path=PATH Specify the directory in which to search for
imports. May be specified multiple times;
directories will be searched in order. If not
given, the current working directory is used.
--version Show version info and exit.
-h, --help Show this text and exit.
--encode=MESSAGE_TYPE Read a text-format message of the given type
from standard input and write it in binary
to standard output. The message type must
be defined in PROTO_FILES or their imports.
--decode=MESSAGE_TYPE Read a binary message of the given type from
standard input and write it in text format
to standard output. The message type must
be defined in PROTO_FILES or their imports.
--decode_raw Read an arbitrary protocol message from
standard input and write the raw tag/value
pairs in text format to standard output. No
PROTO_FILES should be given when using this
flag.
-oFILE, Writes a FileDescriptorSet (a protocol buffer,
--descriptor_set_out=FILE defined in descriptor.proto) containing all of
the input files to FILE.
--include_imports When using --descriptor_set_out, also include
all dependencies of the input files in the
set, so that the set is self-contained.
--include_source_info When using --descriptor_set_out, do not strip
SourceCodeInfo from the FileDescriptorProto.
This results in vastly larger descriptors that
include information about the original
location of each decl in the source file as
well as surrounding comments.
--dependency_out=FILE Write a dependency output file in the format
expected by make. This writes the transitive
set of input file paths to FILE
--error_format=FORMAT Set the format in which to print errors.
FORMAT may be ‘gcc‘ (the default) or ‘msvs‘
(Microsoft Visual Studio format).
--print_free_field_numbers Print the free field numbers of the messages
defined in the given proto files. Groups share
the same field number space with the parent
message. Extension ranges are counted as
occupied fields numbers.

--plugin=EXECUTABLE Specifies a plugin executable to use.
Normally, protoc searches the PATH for
plugins, but you may specify additional
executables not in the path using this flag.
Additionally, EXECUTABLE may be of the form
NAME=PATH, in which case the given plugin name
is mapped to the given executable even if
the executable‘s own name differs.
--cpp_out=OUT_DIR Generate C++ header and source.
--csharp_out=OUT_DIR Generate C# source file.
--java_out=OUT_DIR Generate Java source file.
--javanano_out=OUT_DIR Generate Java Nano source file.
--js_out=OUT_DIR Generate JavaScript source.
--objc_out=OUT_DIR Generate Objective C header and source.
--python_out=OUT_DIR Generate Python source file.
--ruby_out=OUT_DIR Generate Ruby source file.
```

Protobuf 的不足

Protbuf 與 XML 相比也有不足之處。它功能簡單,無法用來表示復雜的概念。
XML 已經成為多種行業標準的編寫工具,Protobuf 只是 Google 公司內部使用的工具,在通用性上還差很多。
由於文本並不適合用來描述數據結構,所以 Protobuf 也不適合用來對基於文本的標記文檔(如 HTML)建模。另外,由於 XML 具有某種程度上的自解釋性,它可以被人直接讀取編輯,在這一點上 Protobuf 不行,它以二進制的方式存儲,除非你有 .proto 定義,否則你沒法直接讀出 Protobuf 的任何內容【 2 】。

參考文獻

  • 官網readme
  • potobuf與JAVA
  • protobuf協議語言指南
  • 在Java中使用Protocol Buffers
  • Protocol Buffer技術詳解(Java實例)

tips:本文屬於自己學習和實踐過程的記錄,很多圖和文字都粘貼自網上文章,沒有註明引用請包涵!如有任何問題請留言或郵件通知,我會及時回復。

Google Protocol Buffer入門