Google.Protobuf工具在C#中的使用方法_第1页
Google.Protobuf工具在C#中的使用方法_第2页
Google.Protobuf工具在C#中的使用方法_第3页
Google.Protobuf工具在C#中的使用方法_第4页
Google.Protobuf工具在C#中的使用方法_第5页
已阅读5页,还剩7页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

第Google.Protobuf工具在C#中的使用方法protobuf是一个语言无关、平台无关的序列化协议,由谷歌开源提供。再加上其高性能、存储占用更小等特点,在云原生的应用中越来越广泛。

在C#中主要有两种方法来使用protobuf协议,nuget包分别为Google.Protobuf和protobuf-net,其中Google.Protobuf由谷歌官方提供。本文简要记录和展示Google.Protobuf的使用方法和特点。

项目资料及文档

项目官网:/protocol-buffershl=zh-cn

github主页:/protocolbuffers/protobuf/

官方文档:/protocol-buffers/docs/overviewhl=zh-cn

该nuget包支持.NETFramework4.5、.NETStandard1.1、.net5等

需要用到的nuget有如下两个:Google.Protobuf、Google.Protobuf.Tools,其中Google.Protobuf是主类库,运行时要用到。Google.Protobuf.Tools提供了命令行工具,用于根据.proto文件转为目标语言的类型,仅开发时使用,运行时不需要。

本次Demo使用的.proto文件内容如下:

syntax="proto3";

optioncc_enable_arenas=true;

packageTccc.Demo.Protobuf;

messageErrorLog{

stringLogID=1;

stringContext=2;

stringStack=3;

}

首先需要根据.proto文件生成目标类型,操作如下:

./tobuf.tools\3.19.1\tools\windows_x64\protoc.exe--csharp_out=./generatedCode./proto/ErrorLto

其中--csharp_out选项是生成C#语言的目标类型,运行protoc.exe-h查看帮助信息,可以看到还支持一下几种选项:

--proto_path=PATH

--cpp_out=OUT_DIRGenerateC++headerandsource.

--csharp_out=OUT_DIRGenerateC#sourcefile.

--java_out=OUT_DIRGenerateJavasourcefile.

--js_out=OUT_DIRGenerateJavaScriptsource.

--kotlin_out=OUT_DIRGenerateKotlinfile.

--objc_out=OUT_DIRGenerateObjective-Cheaderandsource.

--php_out=OUT_DIRGeneratePHPsourcefile.

--python_out=OUT_DIRGeneratePythonsourcefile.

--ruby_out=OUT_DIRGenerateRubysourcefile.

运行上述命令,会根据指定的ErrorLto文件生成ErrorLog.cs文件,文件中就是C#类型ErrorLog。生成的代码中会给此类型增加方法voidWriteTo(CodedOutputStreamoutput)和只读属性Parser,接下来进行序列化和反序列化的关键。

生成的ErrorLog类的完整代码:

//auto-generated

//Generatedbytheprotocolbuffercompiler.DONOTEDIT!

//source:ProtoFiles/ErrorLto

///auto-generated

#pragmawarningdisable1591,0612,3021

#regionDesignergeneratedcode

usingpb=global::Google.Protobuf;

usingpbc=global::Google.Protobuf.Collections;

usingpbr=global::Google.Protobuf.Reflection;

usingscg=global::System.Collections.Generic;

namespaceTccc.Demo.Protobuf{

///summaryHolderforreflectioninformationgeneratedfromProtoFiles/ErrorLto/summary

publicstaticpartialclassErrorLogReflection{

#regionDescriptor

///summaryFiledescriptorforProtoFiles/ErrorLto/summary

publicstaticpbr::FileDescriptorDescriptor{

get{returndescriptor;}

privatestaticpbr::FileDescriptordescriptor;

staticErrorLogReflection(){

byte[]descriptorData=global::System.Convert.FromBase64String(

string.Concat(

"ChlQcm90b0ZpbGVzL0Vycm9yTG9nLnByb3RvEhJUY2NjLkRlbW8uUHJvdG9i",

"dWYiOQoIRXJyb3JMb2cSDQoFTG9nSUQYASABKAkSDwoHQ29udGV4dBgCIAEo",

"CRINCgVTdGFjaxgDIAEoCUID+AEBYgZwcm90bzM="));

descriptor=pbr::FileDescriptor.FromGeneratedCode(descriptorData,

newpbr::FileDescriptor[]{},

newpbr::GeneratedClrTypeInfo(null,null,newpbr::GeneratedClrTypeInfo[]{

newpbr::GeneratedClrTypeInfo(typeof(global::Tccc.Demo.Protobuf.ErrorLog),global::Tccc.Demo.Protobuf.ErrorLog.Parser,new[]{"LogID","Context","Stack"},null,null,null,null)

}));

#endregion

#regionMessages

publicsealedpartialclassErrorLog:pb::IMessageErrorLog

#if!GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE

,pb::IBufferMessage

#endif

privatestaticreadonlypb::MessageParserErrorLog_parser=newpb::MessageParserErrorLog(()=newErrorLog());

privatepb::UnknownFieldSet_unknownFields;

[global::System.Diagnostics.DebuggerNonUserCodeAttribute]

[global::System.CodeDom.Compiler.GeneratedCode("protoc",null)]

publicstaticpb::MessageParserErrorLogParser{get{return_parser;}}

[global::System.Diagnostics.DebuggerNonUserCodeAttribute]

[global::System.CodeDom.Compiler.GeneratedCode("protoc",null)]

publicstaticpbr::MessageDescriptorDescriptor{

get{returnglobal::Tccc.Demo.Protobuf.ErrorLogReflection.Descriptor.MessageTypes[0];}

[global::System.Diagnostics.DebuggerNonUserCodeAttribute]

[global::System.CodeDom.Compiler.GeneratedCode("protoc",null)]

pbr::MessageDescriptorpb::IMessage.Descriptor{

get{returnDescriptor;}

[global::System.Diagnostics.DebuggerNonUserCodeAttribute]

[global::System.CodeDom.Compiler.GeneratedCode("protoc",null)]

publicErrorLog(){

OnConstruction();

partialvoidOnConstruction();

[global::System.Diagnostics.DebuggerNonUserCodeAttribute]

[global::System.CodeDom.Compiler.GeneratedCode("protoc",null)]

publicErrorLog(ErrorLogother):this(){

logID_=other.logID_;

context_=other.context_;

stack_=other.stack_;

_unknownFields=pb::UnknownFieldSet.Clone(other._unknownFields);

[global::System.Diagnostics.DebuggerNonUserCodeAttribute]

[global::System.CodeDom.Compiler.GeneratedCode("protoc",null)]

publicErrorLogClone(){

returnnewErrorLog(this);

///summaryFieldnumberforthe"LogID"field./summary

publicconstintLogIDFieldNumber=1;

privatestringlogID_="";

[global::System.Diagnostics.DebuggerNonUserCodeAttribute]

[global::System.CodeDom.Compiler.GeneratedCode("protoc",null)]

publicstringLogID{

get{returnlogID_;}

set{

logID_=pb::ProtoPreconditions.CheckNotNull(value,"value");

///summaryFieldnumberforthe"Context"field./summary

publicconstintContextFieldNumber=2;

privatestringcontext_="";

[global::System.Diagnostics.DebuggerNonUserCodeAttribute]

[global::System.CodeDom.Compiler.GeneratedCode("protoc",null)]

publicstringContext{

get{returncontext_;}

set{

context_=pb::ProtoPreconditions.CheckNotNull(value,"value");

///summaryFieldnumberforthe"Stack"field./summary

publicconstintStackFieldNumber=3;

privatestringstack_="";

[global::System.Diagnostics.DebuggerNonUserCodeAttribute]

[global::System.CodeDom.Compiler.GeneratedCode("protoc",null)]

publicstringStack{

get{returnstack_;}

set{

stack_=pb::ProtoPreconditions.CheckNotNull(value,"value");

[global::System.Diagnostics.DebuggerNonUserCodeAttribute]

[global::System.CodeDom.Compiler.GeneratedCode("protoc",null)]

publicoverrideboolEquals(objectother){

returnEquals(otherasErrorLog);

[global::System.Diagnostics.DebuggerNonUserCodeAttribute]

[global::System.CodeDom.Compiler.GeneratedCode("protoc",null)]

publicboolEquals(ErrorLogother){

if(ReferenceEquals(other,null)){

returnfalse;

if(ReferenceEquals(other,this)){

returntrue;

if(LogID!=other.LogID)returnfalse;

if(Context!=other.Context)returnfalse;

if(Stack!=other.Stack)returnfalse;

returnEquals(_unknownFields,other._unknownFields);

[global::System.Diagnostics.DebuggerNonUserCodeAttribute]

[global::System.CodeDom.Compiler.GeneratedCode("protoc",null)]

publicoverrideintGetHashCode(){

inthash=1;

if(LogID.Length!=0)hash^=LogID.GetHashCode();

if(Context.Length!=0)hash^=Context.GetHashCode();

if(Stack.Length!=0)hash^=Stack.GetHashCode();

if(_unknownFields!=null){

hash^=_unknownFields.GetHashCode();

returnhash;

[global::System.Diagnostics.DebuggerNonUserCodeAttribute]

[global::System.CodeDom.Compiler.GeneratedCode("protoc",null)]

publicoverridestringToString(){

returnpb::JsonFormatter.ToDiagnosticString(this);

[global::System.Diagnostics.DebuggerNonUserCodeAttribute]

[global::System.CodeDom.Compiler.GeneratedCode("protoc",null)]

publicvoidWriteTo(pb::CodedOutputStreamoutput){

#if!GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE

output.WriteRawMessage(this);

#else

if(LogID.Length!=0){

output.WriteRawTag(10);

output.WriteString(LogID);

if(Context.Length!=0){

output.WriteRawTag(18);

output.WriteString(Context);

if(Stack.Length!=0){

output.WriteRawTag(26);

output.WriteString(Stack);

if(_unknownFields!=null){

_unknownFields.WriteTo(output);

#endif

#if!GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE

[global::System.Diagnostics.DebuggerNonUserCodeAttribute]

[global::System.CodeDom.Compiler.GeneratedCode("protoc",null)]

voidpb::IBufferMessage.InternalWriteTo(refpb::WriteContextoutput){

if(LogID.Length!=0){

output.WriteRawTag(10);

output.WriteString(LogID);

if(Context.Length!=0){

output.WriteRawTag(18);

output.WriteString(Context);

if(Stack.Length!=0){

output.WriteRawTag(26);

output.WriteString(Stack);

if(_unknownFields!=null){

_unknownFields.WriteTo(refoutput);

#endif

[global::System.Diagnostics.DebuggerNonUserCodeAttribute]

[global::System.CodeDom.Compiler.GeneratedCode("protoc",null)]

publicintCalculateSize(){

intsize=0;

if(LogID.Length!=0){

size+=1+pb::CodedOutputStream.ComputeStringSize(LogID);

if(Context.Length!=0){

size+=1+pb::CodedOutputStream.ComputeStringSize(Context);

if(Stack.Length!=0){

size+=1+pb::CodedOutputStream.ComputeStringSize(Stack);

if(_unknownFields!=null){

size+=_unknownFields.CalculateSize();

returnsize;

[global::System.Diagnostics.DebuggerNonUserCodeAttribute]

[global::System.CodeDom.Compiler.GeneratedCode("protoc",null)]

publicvoidMergeFrom(ErrorLogother){

if(other==null){

return;

if(other.LogID.Length!=0){

LogID=other.LogID;

if(other.Context.Length!=0){

Context=other.Context;

if(other.Stack.Length!=0){

Stack=other.Stack;

_unknownFields=pb::UnknownFieldSet.MergeFrom(_unknownFields,other._unknownFields);

[global::System.Diagnostics.DebuggerNonUserCodeAttribute]

[global::System.CodeDom.Compiler.GeneratedCode("protoc",null)]

publicvoidMergeFrom(pb::CodedInputStreaminput){

#if!GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE

input.ReadRawMessage(this);

#else

uinttag;

while((tag=input.ReadTag())!=0){

switch(tag){

default:

_unknownFields=pb::UnknownFieldSet.MergeFieldFrom(_unknownFields,input);

break;

case10:{

LogID=input.ReadString();

break;

case18:{

Context=input.ReadString();

break;

case26:{

Stack=input.ReadString();

break;

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

最新文档

评论

0/150

提交评论