.netcore grpc的proto文件字段详解

一、.proto文件字段概述

  1. grpc的接口传输参数都是根据.proto文件约定的字段格式进行传输的
  2. grpc提供了多种类型字段;主要包括标量值类型(基础类型)、日期时间、可为null类型、字节、列表、字典、Any类型(任意类型)、Oneof等
  3. 字段严格规范,是一种强类型文件协议

二、案例介绍

  1. 标量值类型
  2. 日期时间
  3. 可为null类型
  4. 字节
  5. 列表
  6. 字典
  7. Any类型
  8. Oneof:一种语言特性,可以通过该特性进行对象切换处理;使用 oneof 指定可能返回 A对象或B对象 的响应消息

三、服务端定义

  1. 定义通用消息实体
  2. 根据不同的类型创建对应的案例实体
  3. 特殊的字段需要导入指定的包才能使用
  4. 定义引用字段的各个服务接口
  5. 内部实现逻辑,及打印展示相应的字段结果
// 1.提供公共的实体proto文件
// 2.服务引用对应的proto文件// 通用消息文件datamessages.proto
syntax = "proto3";option csharp_namespace = "GrpcProject";package grpc.serviceing;// 基础类型实体
message BaseConfig{string name = 1;double position = 2;float distance= 3 ;int32 age = 4;int64 timeSpanId = 5;uint32 uAge = 6;uint64 uTimeSpanId = 7;sint32 sAge = 8;sint64 sTimeSpanId = 9;bool flag = 10;
}// 日期类型实体 需要导入 日期namespace
import "google/protobuf/duration.proto";
import "google/protobuf/timestamp.proto";message DateConfig{int64 id = 1;google.protobuf.Timestamp dateTimestamp = 2;google.protobuf.Duration dateDuration = 3;
}// 字节类型
message ByteConfig{int64 id = 1;bytes positionBytes = 2;
}// 可为null类型 需要导入 null的namespace
import "google/protobuf/wrappers.proto";message NullConfig{int64 id = 1;google.protobuf.BoolValue nullBool = 2;google.protobuf.DoubleValue nullDoubule = 3;google.protobuf.FloatValue nullFloat = 4;google.protobuf.Int32Value nullInt = 5;google.protobuf.Int64Value nullLong = 6;google.protobuf.UInt32Value nullUInt = 7;google.protobuf.StringValue nullString = 8;google.protobuf.BytesValue nullBytes = 9;
}//  集合类型
message ListConfig{int64 id = 1;// 数组repeated string names = 2;repeated ListDetailConfig details = 3;// 字典map<int32,string> attributes = 4;map<int32,ListDetailConfig> dicDetail = 5;
}message ListDetailConfig{string name = 1;int32 height = 2;
}// 任意类型 需要导入对应的包
import "google/protobuf/any.proto";
message AnyConfig{int32 id = 1;google.protobuf.Any anyObject = 2;
}// Oneof类型  编译器在生成消息类时处理 oneof 关键字。 使用 oneof 指定可能返回 A 或 B 或 C 的响应消息
message OneofConfig{oneof result{A oA = 1;B oB = 2;C oC = 3;}
}message A{int32 id = 1;
}message B{int32 id = 1;
}message C{int32 id =1;
}
// 接口服务定义protofield.proto文件syntax = "proto3";import "google/protobuf/empty.proto";
import "Protos/datamessages.proto";option csharp_namespace = "GrpcProject";package grpc.serviceing;service FieldRpc{// 基础字段处理rpc BaseConfigService(BaseConfig) returns (google.protobuf.Empty);// 日期字段处理rpc DateConfigService(DateConfig) returns (google.protobuf.Empty);// 字节处理rpc ByteConfigService(ByteConfig) returns (google.protobuf.Empty);// null字段处理rpc NullConfigService(NullConfig) returns (google.protobuf.Empty);// 集合类型字段处理rpc ListConfigService(ListConfig) returns (google.protobuf.Empty);// 任意类型字段处理rpc AnyConfigService(AnyConfig) returns (google.protobuf.Empty);// Oneof类型字段处理rpc OneofConfigService(OneofConfig) returns (google.protobuf.Empty);
}
// 服务实现类/// <summary>/// 字段处理服务/// </summary>public class ProtoFieldService : FieldRpc.FieldRpcBase{// 基础配置public override async Task<Empty> BaseConfigService(BaseConfig request, ServerCallContext context){await Console.Out.WriteLineAsync("\r\n--------------------------基础配置--------------------------\r\n");// 打印字段信息var properties = request.GetType().GetProperties();foreach (var property in properties){var value = property.GetValue(request);await Console.Out.WriteLineAsync($"{property.Name}:{value}");}return new Empty();}// 日期配置public override async Task<Empty> DateConfigService(DateConfig request, ServerCallContext context){await Console.Out.WriteLineAsync("\r\n--------------------------日期配置--------------------------\r\n");// timspanvar duration = request.DateDuration.ToTimeSpan();await Console.Out.WriteLineAsync($"{nameof(duration)}:{duration.TotalSeconds}");// datetimevar time = request.DateTimestamp.ToDateTime();await Console.Out.WriteLineAsync($"{nameof(time)}:{time:yyyy-MM-dd HH:mm:ss}");return new Empty();}// 字节public override async Task<Empty> ByteConfigService(ByteConfig request, ServerCallContext context){await Console.Out.WriteLineAsync("\r\n--------------------------字节配置--------------------------\r\n");var bytes = request.PositionBytes.ToByteArray();var message = Encoding.UTF8.GetString(bytes, 0, bytes.Length);await Console.Out.WriteLineAsync($"{nameof(message)}:{message}");return new Empty();}// null配置public override async Task<Empty> NullConfigService(NullConfig request, ServerCallContext context){await Console.Out.WriteLineAsync("\r\n--------------------------null配置--------------------------\r\n");// 打印字段信息var properties = request.GetType().GetProperties();foreach (var property in properties){var value = property.GetValue(request);var printValue = value == null ? "返回null值" : value;await Console.Out.WriteLineAsync($"{property.Name}:{printValue}");}return new Empty();}// 集合public override async Task<Empty> ListConfigService(ListConfig request, ServerCallContext context){await Console.Out.WriteLineAsync("\r\n--------------------------集合配置--------------------------\r\n");var id = request.Id;await Console.Out.WriteLineAsync($"主键标识:{id}\r\n");// 转换数组arrayawait Console.Out.WriteLineAsync($"打印names信息:");var names = request.Names.ToArray();foreach (var name in names){await Console.Out.WriteLineAsync(name);}// 转换listawait Console.Out.WriteLineAsync($"\r\n打印detailList信息:");var detailList = request.Details.ToList();foreach (var item in detailList){await Console.Out.WriteLineAsync($"ListDetailConfig:{nameof(item.Name)}  {item.Name};{nameof(item.Height)}  {item.Height}。");}// 字典await Console.Out.WriteLineAsync($"\r\n打印一般字典信息:");var dicAttributes = request.Attributes.ToDictionary(t => t.Key, t => t.Value);foreach (var attr in dicAttributes){await Console.Out.WriteLineAsync($"key:{attr.Key};value:{attr.Value}。");}await Console.Out.WriteLineAsync($"\r\n打印对象字典信息:");foreach (var item in request.DicDetail){await Console.Out.WriteLineAsync($"key:{item.Key};value:{item.Value.Name} | {item.Value.Height}。");}return new Empty();}// Anypublic override async Task<Empty> AnyConfigService(AnyConfig request, ServerCallContext context){await Console.Out.WriteLineAsync("\r\n--------------------------Any配置--------------------------\r\n");var anyObject = request.AnyObject;// 检查是否是A对象if (anyObject.Is(A.Descriptor)){var a = anyObject.Unpack<A>();if (a is not null){await Console.Out.WriteLineAsync($"A对象:{a.Id}");}}else if (anyObject.Is(B.Descriptor)){var b = anyObject.Unpack<B>();if (b is not null){await Console.Out.WriteLineAsync($"B对象:{b.Id}");}}else if (anyObject.Is(C.Descriptor)){var c = anyObject.Unpack<C>();if (c is not null){await Console.Out.WriteLineAsync($"C对象:{c.Id}");}}else{await Console.Out.WriteLineAsync("Any未解析到任何对象");}return new Empty();}// oneofpublic override async Task<Empty> OneofConfigService(OneofConfig request, ServerCallContext context){await Console.Out.WriteLineAsync("\r\n--------------------------Oneof配置--------------------------\r\n");// 检测对应的对象是否有值switch (request.ResultCase){case OneofConfig.ResultOneofCase.None:await Console.Out.WriteLineAsync("未检测到任何对象");break;case OneofConfig.ResultOneofCase.OA:await Console.Out.WriteLineAsync($"对象OA存在值:{request.OA.Id}");break;case OneofConfig.ResultOneofCase.OB:await Console.Out.WriteLineAsync($"对象OB存在值:{request.OB.Id}");break;case OneofConfig.ResultOneofCase.OC:await Console.Out.WriteLineAsync($"对象OC存在值:{request.OC.Id}");break;default:break;}return new Empty();}}

三、客户端定义

  1. 引用proto文件,配置为客户端类型
  2. 根据编译生成的函数进行传参调用
  3. 创建WPF测试客户端
  4. 各个服务接口创建对应的按钮进行调用
  5. 执行过程中,服务端控制台会打印对应的消息

        // 基础private async void BtnBaseconfig_Click(object sender, RoutedEventArgs e){await WpfFieldClient.Show(1);MessageBox();}// 日期private async void BtnDateconfig_Click(object sender, RoutedEventArgs e){await WpfFieldClient.Show(2);MessageBox();}// 字节private async void BtnByteconfig_Click(object sender, RoutedEventArgs e){await WpfFieldClient.Show(3);MessageBox();}// nullprivate async void BtnNullconfig_Click(object sender, RoutedEventArgs e){await WpfFieldClient.Show(4);MessageBox();}// listprivate async void BtnListconfig_Click(object sender, RoutedEventArgs e){await WpfFieldClient.Show(5);MessageBox();}// anyprivate async void BtnAnyconfig_Click(object sender, RoutedEventArgs e){await WpfFieldClient.Show(6);MessageBox();}// Oneofprivate async void BtnOneofconfig_Click(object sender, RoutedEventArgs e){await WpfFieldClient.Show(7);MessageBox();}

调用的类库:

    public class WpfFieldClient{/// <summary>/// 根据参数选择不同的方法执行/// </summary>/// <param name="k"></param>public static async Task Show(int k){var channel = GrpcChannel.ForAddress("https://localhost:7188");var client = new GrpcProject.FieldRpc.FieldRpcClient(channel);// 基础BaseConfig config = new BaseConfig();config.Name = "张三";config.Position = 2.33D;config.Distance = 5.48F;config.Age = 10;config.TimeSpanId = 6538590027736100;config.SAge = 1921;config.STimeSpanId = 6538590027736130;config.Flag = true;// 日期DateConfig dateConfig = new DateConfig();dateConfig.Id = 179;dateConfig.DateDuration = Duration.FromTimeSpan(TimeSpan.FromSeconds(5));// 注意这里的时间是utc时间dateConfig.DateTimestamp = Timestamp.FromDateTime(DateTime.UtcNow);// 字节ByteConfig byteConfig = new ByteConfig();byteConfig.Id = 9854564654654;byteConfig.PositionBytes = ByteString.CopyFrom(Encoding.UTF8.GetBytes("庄这人的南的很"));// nullNullConfig nullConfig = new NullConfig();nullConfig.Id = 1854564654654;nullConfig.NullBool = true;nullConfig.NullFloat = null;nullConfig.NullUInt = null;nullConfig.NullInt = 15;nullConfig.NullLong = 112345451234787;// ListConfigListConfig listConfig = new ListConfig();var attributes = new Dictionary<int, string>{[1] = "one",[2] = "two",[3] = "three",[4] = "four",[5] = "five"};listConfig.Id = 123456456;listConfig.Attributes.Add(attributes);var dicDetail = new Dictionary<int, ListDetailConfig>{[1] = new ListDetailConfig { Height = 1, Name = "one" },[2] = new ListDetailConfig { Height = 2, Name = "two" },[3] = new ListDetailConfig { Height = 3, Name = "three" },[4] = new ListDetailConfig { Height = 4, Name = "four" },[5] = new ListDetailConfig { Height = 5, Name = "five" }};listConfig.DicDetail.Add(dicDetail);listConfig.Details.Add(new ListDetailConfig { Height = 8, Name = "Eight" });var detailConfigs = new List<ListDetailConfig>{new ListDetailConfig { Height=9,Name="nine"},new ListDetailConfig{ Height=10,Name="ten"}};listConfig.Details.Add(detailConfigs);// AnyAnyConfig anyConfig = new AnyConfig();anyConfig.Id = 42564134;anyConfig.AnyObject = Any.Pack(new B { Id = 15 });// OneofOneofConfig oneofConfig = new OneofConfig();oneofConfig.OA = new A { Id = 1 };//oneofConfig.OC = new C { Id = 2 };var emptyResult = k switch{1 => await client.BaseConfigServiceAsync(config),2 => await client.DateConfigServiceAsync(dateConfig),3 => await client.ByteConfigServiceAsync(byteConfig),4 => await client.NullConfigServiceAsync(nullConfig),5 => await client.ListConfigServiceAsync(listConfig),6 => await client.AnyConfigServiceAsync(anyConfig),7 => await client.OneofConfigServiceAsync(oneofConfig),_ => new Empty()};}}

五、执行结果

服务端:

 客户端:

 六、源码地址

链接:https://pan.baidu.com/s/150TKY2Kgln3l_uKAsztyzw 
提取码:hkb9

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/41775.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

前端笔试+面试分享

以下是个人线下面试遇到的真实的题&#xff0c;仅供参考和学习 1. css 选择符有哪些&#xff1f;哪些属性可以继承&#xff1f;优先级算法加何计算&#xff1f; CSS选择符有很多种&#xff0c;例如类型选择器、类选择器、ID选择器、属性选择器、伪类选择器、伪元素选择器等。 …

Algorithem Review 5.2 图论

网络流 设源点为 s s s&#xff0c;汇点为 t t t&#xff0c;每条边 e e e 的流量上限为 c ( e ) c(e) c(e)&#xff0c;流量为 f ( e ) f(e) f(e)。割 指对于某一顶点集合 P ⊂ V P \subset V P⊂V&#xff0c;从 P P P 出发指向 P P P 外部的那些原图中的边的集合&a…

回归预测 | MATLAB实现基于SSA-KELM-Adaboost麻雀算法优化核极限学习机结合AdaBoost多输入单输出回归预测

回归预测 | MATLAB实现基于SSA-KELM-Adaboost麻雀算法优化核极限学习机结合AdaBoost多输入单输出回归预测 目录 回归预测 | MATLAB实现基于SSA-KELM-Adaboost麻雀算法优化核极限学习机结合AdaBoost多输入单输出回归预测预测效果基本介绍模型描述程序设计参考资料 预测效果 基本…

SSH远程连接MacOS catalina并进行终端颜色配置

一、开关SSH服务 在虚拟机上安装了MacOS catalina&#xff0c;想要使用SSH远程进行连接&#xff0c;但是使用“系统偏好设置”/“共享”/“远程登录”开关进行打开&#xff0c;却一直是正在启动“远程登录”&#xff1a; 难道是catalina有BUG&#xff1f;不过还是有方法的&…

第07天 Static关键字作用及用法

✅作者简介&#xff1a;大家好&#xff0c;我是Leo&#xff0c;热爱Java后端开发者&#xff0c;一个想要与大家共同进步的男人&#x1f609;&#x1f609; &#x1f34e;个人主页&#xff1a;Leo的博客 &#x1f49e;当前专栏&#xff1a;每天一个知识点 ✨特色专栏&#xff1a…

【前端|Javascript第5篇】全网最详细的JS的内置对象文章!

前言 在当今数字时代&#xff0c;前端技术正日益成为塑造用户体验的关键。我们在开发中需要用到很多js的内置对象的一些属性来帮助我们更快速的进行开发。或许你是刚踏入前端领域的小白&#xff0c;或者是希望深入了解内置对象的开发者&#xff0c;不论你的经验如何&#xff0c…

MATLAB中的代数环概念

在 Simulink 模型中&#xff0c;当存在信号环并且信号环中只存在直接馈通模块时&#xff0c;将出现代数环。直接馈通表示 Simulink 需要模块输入信号的值来计算当前时间步的输出。这种信号循环会在同一时间步中产生模块输出和输入的循环依存关系。这会导致一个需要在每个时间步…

【【verilog典型电路设计之流水线结构】】

verilog典型电路设计之流水线结构 下图是一个4位的乘法器结构&#xff0c;用verilog HDL 设计一个两级流水线加法器树4位乘法器 对于流水线结构 其实需要做的是在每级之间增加一个暂存的数据用来存储 我们得到的东西 我们一般来说会通过在每一级之间插入D触发器来保证数据的联…

OpenCV-Python中的图像处理-图像特征

OpenCV-Python中的图像处理-图像特征 图像特征Harris角点检测亚像素级精度的角点检测Shi-Tomasi角点检测SIFT(Scale-Invariant Feature Transfrom)SURF(Speeded-Up Robust Features)FAST算法BRIEF(Binary Robust Independent Elementary Features)算法ORB (Oriented FAST and R…

python编程中有哪些方便的调试方法

大家好&#xff0c;给大家分享一下一个有趣的事情&#xff0c;很多人还不知道这一点。下面详细解释一下。现在让我们来看看&#xff01; 对于每个程序开发者来说&#xff0c;调试几乎是必备技能。常用Pycharm编辑器里的方法有Print大法、log大法&#xff0c;但缺少类似Matlab的…

怎么开通Tik Tok海外娱乐公会呢?

TikTok作为全球知名的社交媒体平台&#xff0c;吸引了数亿用户的关注和参与。许多公司和个人渴望通过开通TikTok直播公会进入这一领域&#xff0c;以展示自己的创造力和吸引更多粉丝。然而&#xff0c;成为TikTok直播公会并非易事&#xff0c;需要满足一定的门槛和申请找cmxyci…

【日常积累】Linux之init系统学习

init系统简介: Linux 操作系统的启动首先从 BIOS 开始&#xff0c;接下来进入 boot loader&#xff0c;由 bootloader 载入内核&#xff0c;进行内核初始化。内核初始化的最后一步就是启动 pid 为 1 的 init 进程&#xff0c;这个进程是系统的第一个进程&#xff0c;它负责产生…

银河麒麟服务器v10 sp1 .Net6.0 上传文件错误

上一篇&#xff1a;银河麒麟服务器v10 sp1 部署.Net6.0 http https_csdn_aspnet的博客-CSDN博客 .NET 6之前&#xff0c;在Linux服务器上安装 libgdiplus 即可解决&#xff0c;libgdiplus是System.Drawing.Common原生端跨平台实现的主要提供者&#xff0c;是开源mono项目。地址…

ubuntu 部署 ChatGLM-6B 完整流程 模型量化 Nvidia

ubuntu 部署 ChatGLM-6B 完整流程 模型量化 Nvidia 初环境与设备环境准备克隆模型代码部署 ChatGLM-6B完整代码 ChatGLM-6B 是一个开源的、支持中英双语的对话语言模型&#xff0c;基于 General Language Model (GLM) 架构&#xff0c;具有 62 亿参数。结合模型量化技术&#x…

力扣 322. 零钱兑换

题目来源&#xff1a;https://leetcode.cn/problems/coin-change/description/ C题解&#xff08;来源代码随想录&#xff09;&#xff1a;题目中说每种硬币的数量是无限的&#xff0c;可以看出是典型的完全背包问题。动规五部曲分析如下&#xff1a; 确定dp数组以及下标的含义…

原码、反码、补码,进制转换,有符号数和无符号数转换

计算机底层存储数据时&#xff0c;存储的是数据对应的二进制数字。对于整型数据&#xff0c;其二进制表示形式有三种&#xff0c;分别是&#xff1a;原码、反码、补码&#xff0c;而实际存储的是整型数据的补码。 原码、反码以及补码都是有符号的&#xff0c;其中最高位存放符…

带你掌握Stable Diffution商业级玩法

课程介绍 学习地址 《Stable Diffusion商业级玩法》通过详细讲解AI绘画技巧、实操演示和个性化指导&#xff0c;帮助您从零基础成为绘画高手&#xff0c;帮助您有效推广产品或服务&#xff0c;提升市场份额。教您掌握稳定扩散绘画技巧&#xff0c;开启艺术创作新篇章。

Opencv 之ORB特征提取与匹配API简介及使用例程

Opencv 之ORB特征提取与匹配API简介及使用例程 ORB因其速度较快常被用于视觉SLAM中的位姿估计、视觉里程、图像处理中的特征提取与匹配及图像拼接等领域本文将详细给出使用例程及实现效果展示 1. API 简介 创建 static Ptr<ORB> cv::ORB::create (int nfeatures 500…

无涯教程-Perl - use函数

描述 此函数将MODULE导出的所有功能(或仅LIST引用的功能)导入当前包的名称空间。有效等效于- BEGIN { require "Module.pm"; Module->import(); }也用于在当前脚本上强加编译器指令(编译指示),尽管从本质上讲它们只是模块。 请注意,use语句在编译时进行判断。在…

springcloud3 hystrix实现服务熔断的案例配置3

一 hystrix的熔断原理 1.1 hystrix的熔断原理 在springcloud的框架里&#xff0c;熔断机制是通过hystrix实现&#xff0c;hystrix会监控服务之间的调用。当失败调用达到一定的阈值&#xff0c;默认是5s内失败20次&#xff0c;就会启用hystrix的熔断机制&#xff0c;使用命Hy…