protobuf使用

一、protobuf

简介:略

安装:

1)下载protobuf源码: http://code.google.com/p/protobuf/downloads/list

这份源码主要用户将.proto文件生成c++,python,java代码,这也是google默认支持的三种

     2)编译安装

tar -xzf protobuf-2.1.0.tar.gz 

  cd protobuf-2.1.0 
  ./configure --prefix=/usr/local/protobuf
  make 
  make check 
  make install 
3)配置环境变量
sudo vim /etc/profile
  添加
export PATH=$PATH:/usr/local/protobuf/bin/
export PKG_CONFIG_PATH=/usr/local/protobuf/lib/pkgconfig/
保存执行
source /etc/profile

使用:
1)编写.proto文件

message Person {
  required string name = 1;///sdfsfsdffds
  required int32 id = 2;
  optional string email = 3;


  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }
  repeated PhoneType pt = 7;
  message PhoneNumber1 {
    required string aaa = 1;
    optional uint64 bb =2;
  }
  repeated PhoneNumber phone = 4;
  repeated PhoneNumber1 phone1 = 6;
}

protobuf消息布局


protobuf消息布局都已“message msgname”开首,此中msgname是你要定义的消息段名,这里为Persson;


接下来一般每一行都是类似于 “润饰词 数据类型 数据名字 = 序号 [default=默认值]”,


润饰词有required,optional,repeated三种,required默示该值是必必要传的,并且只能呈现一个;optional该值可以有零个或一个,可以查询其存在与否;repeated该值相当于一个数组或有序列表,改值可为0个、1个、或多个,可以应用选项packed = true来进行高效的编码。

2)使用。proto文件生成代码
protoc --proto_path=IMPORT_PATH --cpp_out=DST_DIR --java_out=DST_DIR --python_out=DST_DIR path/to/file.proto
IMPORT_PATH:proto文件路径
--cpp_out:输出c++代码
--java_out:输出java代码
--python_out:输出python代码
最后一个选项是proto文件名


二、protobuf与php
1、安装php扩展
https://github.com/allegro/php-protobuf/
进入解压目录执行: phpize
./configure --with-php-config=php-config
make
make install

 未完待续......

你可能感兴趣的:(protobuf使用)