首页 > 其他分享 >Protobuf详解与使用

Protobuf详解与使用

时间:2024-07-19 21:55:27浏览次数:13  
标签:int32 Protobuf mobile required records 详解 使用 message string

目录

一、Protobuf序列化概述

二、Protobuf的原理

三、protobuf 的安装

四、定义message

五、编译message文件

六、应用Protobuf

七、Message的使用

1、Message的基本用法

2、Message的嵌套使用


一、Protobuf序列化概述

protobuf是一种比json和xml等序列化工具更加轻量和高效的结构化数据存储格式,性能比json和xml真的强很多,毕竟google出品。

官网:https://developers.google.com/protocol-buffers/icon-default.png?t=N7T8https://developers.google.com/protocol-buffers/

二、Protobuf的原理

三、protobuf 的安装

apt-get install autoconf automake libtool curl make g++ unzip
$ git clone https://github.com/protocolbuffers/protobuf.git 
$ cd protobuf 
$ git submodule update --init --recursive 
$ ./autogen.sh 
$ ./configure 
$ make 
$ make check 
$ sudo make install 
$ sudo ldconfig 

四、定义message

所有的message必须定义到一个文件中,且文件的后缀名为.proto。例如我们定义的bike.proto文件

syntax = "proto2";

package tutorial;

message mobile_request
{
    required string mobile = 1;
}

message mobile_response
{
    required int32 code   = 1;   //响应代号
    required int32 icode  = 2;   //验证码
    optional string data  = 3;   //失败原因
}


message login_request
{
    required string mobile  = 1;    // 手机号码
    required int32  icode   = 2;    // 验证码
}


message login_response
{
    required int32   code   = 1;    // 响应代号
    optional string  desc   = 2;    // 验证码
}

message recharge_request
{
    required string mobile  = 1;    // 手机号码
    required int32  amount  = 2;    // 充值金额
}


message recharge_response
{
    required int32   code   = 1;    // 响应代号
    optional string  desc   = 2;    // 验证码
    required int32  balance = 3;    // 最新的余额
}

message account_balance_request
{
    required string mobile = 1;
}

message account_balance_response
{
    required int32   code   = 1;    // 响应代号
    optional string  desc   = 2;    // 验证码
    required int32  balance = 3;
}

message list_account_records_request
{
    required string mobile = 1;
}

message list_account_records_response
{
    required int32   code   = 1;    // 响应代号
    optional string  desc   = 2;    // 验证码
    message account_record
    {
        required int32  type      = 1; // 0 : 骑行消费,  1 : 充值, 2 : 退款
        required int32  limit     = 2; // 消费或者充值金额
        required uint64 timestamp = 3; // 记录发生时的时间戳
    }

    repeated account_record records = 3;
}

message list_travel_records_request
{
    required string mobile = 1;
}

message list_travel_records_response
{
    required int32   code   = 1;    // 响应代号
    optional string  desc   = 2;    // 验证码
    message travel_record
    {
        required uint64 stm      = 1;   // start timestamp
        required uint32 duration = 2;   // 骑行时长
        required uint32 amount   = 3;   // 所耗金额
    }

    required double              mileage   = 3; // 里程
    required double              discharge = 4; // 排放
    required double              calorie   = 5; // 卡路里
    repeated travel_record       records   = 6;
}

五、编译message文件

编译语法:

protoc -I=$SRC_DIR --cpp_out=$DST_DIR  bike.proto

SRC_DIR 表示proto文件所在的目录,cpp_out指定了生成的代码的路径, bike.proto指proto文件名。

protoc -I=./ --cpp_out=./ bike.proto

这样在当前目录生成了bike.pb.cc和bike.pb.h两个文件。

编译生成的c++文件

g++  -std=c++11   example.cc bike.pb.cc -lprotobuf

六、应用Protobuf

把生成了protocol.pb.cc和protocol.pb.h加入到工程,那么接着就是调用一些API,完成序列化和反序列化。
API说明  : https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.messageicon-default.png?t=N7T8https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.message

七、Message的使用

1、Message的基本用法

范例1: example1.cc

#include "bike.pb.h"
#include <string>
#include <iostream>


using namespace std;
using namespace tutorial;


int main(void)
{
    std::string data;   //存储序列化的消息

    //客户端发送请求
    {
        mobile_request mr;
        mr.set_mobile("18684518289");

        mr.SerializeToString(&data);
        cout<<"序列化后的数据["<<data.length()<<"]: "<< data << endl;
        cout<<hex<<(int)*((char*)data.c_str())<<endl;
        cout<<hex<<(int)*((char*)data.c_str() + 1)<<endl;
        //客户端发送data  send(sockfd, data.c_str(), data.length());
    }
    //服务器端接受请求
    {
        //receive(sockfd, data, ...);
        mobile_request mr;
        mr.ParseFromString(data);
        cout<<"客户端手机号码: " << mr.mobile() << endl;

    }

    return 0;
}

2、Message的嵌套使用

范例2: example1.cc

#include "bike.pb.h"
#include <string>
#include <iostream>

using namespace std;
using namespace tutorial;


int main(void)
{
    std::string data;   //存储序列化的消息

    //客户端发送请求
    {
        list_account_records_response larr;
        larr.set_code(200);
        larr.set_desc("ok");

        for(int i=0; i<5; i++)
        {
            list_account_records_response_account_record * ar = larr.add_records();
            ar->set_type(0);
            ar->set_limit(i * 100);
            ar->set_timestamp(time(NULL));
        }

        printf("recoreds size : %d\n", larr.records_size());
        larr.SerializeToString(&data);
        //客户端发送data  send(sockfd, data.c_str(), data.length());
    }
    //服务器端接受请求
    {
        list_account_records_response larr;
        larr.ParseFromString(data);

        printf("recoreds size : %d\n", larr.records_size());
        printf("code: %d\n", larr.code());
        for(int i=0; i<larr.records_size(); i++)
        {
            const list_account_records_response_account_record &ar = larr.records(i);
            printf("limit: %d\n", ar.limit());
        }
        //cout<<"客户端手机号码: " << mr.mobile() << endl;
    }

    return 0;
}

标签:int32,Protobuf,mobile,required,records,详解,使用,message,string
From: https://blog.csdn.net/m0_65635427/article/details/140440902

相关文章

  • MySQL数据库基本操作以及使用
    MySQL数据库操纵数据库查看数据库showdatabases;创建数据库createdatabase<database_name>;删除数据库dropdatabase<database_name>;使用数据库usemysql操纵数据表查看数据表showtables;创建数据表CREATETABLETBL_USER(#创建user,tableU_IDINTPR......
  • Java基础-详解String类
    为什么String类是不可变的publicfinalclassString{privatefinalchar[]value;}由以上String类的源码可以看出,String类内部使用字符数组char[]来存储字符串(Java9后修改为byte[]字节数组),而且数组被final修饰且为私有的,String类没有提供修改该字符串方法,以及由于S......
  • 函数的定义使用和种类
    open函数是Python中用于打开文件的内置函数,它返回一个文件对象,该对象提供了许多用于文件操作的方法,如读取、写入、追加等。使用open函数时,你需要指定文件名和模式(如只读、只写、追加等)。读取文件#打开文件并读取内容withopen('example.txt','r')asfile:......
  • Java关于注解的使用、如何自定义注解、如何通过元注解解析注解
    注解的介绍Java中总共有五大引用数据类型:类、数组、接口、枚举、注解。其中注解是在jdk1.5版本中加进来的特性,和类,接口,枚举是同一个层次的。注解应用:说明:一般用来对代码进行说明,方便生成doc文档(API文档)检查:检查代码是否符合条件@Override(检查重写方法)@FunctionalInter......
  • Git 的介绍和使用方法
    Git是什么?Git是目前世界上最先进的分布式版本控制系统(类似于同时协作,每个人负责一个模块后上传到分支dev下,负责人审核过后合并到master中)。下载方法和安装直接到官网下载后,默认安装。Git-安装Git打开在桌面按着shift键同时鼠标右键会出现一个OpenGitBashhere单击......
  • java数组之数组工具类——Arrays的使用
    一、Arrays工具类简述    在java的类库中有许多现成的已经封装好的方法,可以供开发人员使用,比如我们之前学的二分法查找或者快速排序等。所以在实际的开发中,我们是不用自己编写这些常用的方法的。那么在常用的数组方法在哪里的?java作为面向对象的语言,所有方法都会封装......
  • [米联客-安路飞龙DR1-FPSOC] FPGA基础篇连载-02使用安路TD开发工具创建FPGA工程
    软件版本:Anlogic-TD5.9.1-DR1_ES1.1操作系统:WIN1064bit硬件平台:适用安路(Anlogic)FPGA实验平台:米联客-MLK-L1-CZ06-DR1M90G开发板板卡获取平台:https://milianke.tmall.com/登录"米联客"FPGA社区http://www.uisrc.com视频课程、答疑解惑!1概述本实验以FPGA芯片DR1M9......
  • vue路由守卫的使用方法和应用场景
    全局守卫beforeEach中三个属性router.beforeEach((to,from,next)=>{  if(!localStorage.getItem("token")){  if(to.path!=="/login"){   returnnext("/login")  } } next()})路由独享守卫 constroutes=[ {  pat......
  • 使用Memcached加速Web应用程序
    使用Memcached加速Web应用程序1.介绍Memcached基本概念Memcached:一个高性能的分布式内存对象缓存系统,用于加速动态Web应用程序。工作原理:将数据存储在内存中,从而减少对数据库的读取次数,提高数据读取速度。为什么使用Memcached减少数据库负载:通过缓存频繁访问的数据,降......
  • 查看当前使用的 WSL 发行版
    查看当前使用的WSL发行版1.打开Windows命令提示符(Cmd)或PowerShell窗口。2.输入以下命令查看已安装的WSL发行版列表以及默认发行版:wsl-l-v该命令将显示所有已安装的WSL发行版的列表及其版本,并标明当前的默认发行版。例如:NAMESTATE......