protobuf支持vs2019_vs2019 .net core 3.1 使用GRPC 多个proto文件

本文档详细介绍了如何在VS2019中使用.NET Core 3.1构建GRPC服务端和客户端,涉及到protobuf的proto文件创建、服务端代码生成、服务注册、配置HTTP2以及客户端调用。通过实例展示了服务端Proto文件定义、服务类实现、 Startup类配置和服务调用的方法。
摘要由CSDN通过智能技术生成

服务端:

1.使用vs2019创建GRPC服务端

2.在项目下的Protos文件夹创建.proto文件

内容设置如下:

syntax = "proto3";//命名空间

option csharp_namespace = "GrpcService1";

package first;//定义的服务

service ProFirst {//方法

rpc SayHello (LxpRequest) returns (LxpReply);//方法

rpc GetUserInfo(LxpRequest) returns(LxpReply);

}//请求体

message LxpRequest {string name = 1;string age = 4;

}//响应体

message LxpReply {string message = 1;

}

3.右键项目->编辑项目文件->将创建的.proto文件添加进去,vs2019自动生成代码

netcoreapp3.1

设置完成会在项目的obj>debug>netcoreapp3.1目录下自动生成对应的代码

3.在项目下的Services文件

在Service文件夹添加类,让该类继承proto自动生成的代码,并且重写,这里需要注意的是 每次在proto文件新增方法的时候需要在该文件实现,否则会调用错误,报未实现的错误

usingGrpc.Core;usingMicrosoft.Extensions.Logging;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Reflection.Metadata.Ecma335;usingSystem.Threading.Tasks;namespaceGrpcService1

{//这里继承proto文件生成的服务抽象类,需要自己实现

public classFirstService : ProFirst.ProFirstBase

{private readonly ILogger_logger;public FirstService(ILoggerlogger)

{

_logger=logger;

}public override bool Equals(objectobj)

{return base.Equals(obj);

}public override intGetHashCode()

{return base.GetHashCode();

}public override TaskGetUserInfo(LxpRequest request, ServerCallContext context)

{return Task.FromResult(new LxpReply { Message = "LXP 我爱你"});

}public override TaskSayHello(LxpRequest request, ServerCallContext context)

{return Task.FromResult(new LxpReply { Message = "LXP 你好"});

}public override stringToString()

{return base.ToString();

}

}

}

4.在startup类文件配置grpc

startup文件中需要启用,在ConfigureServices注册服务,Configure设置服务的终结点

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;usingMicrosoft.AspNetCore.Builder;usingMicrosoft.AspNetCore.Hosting;usingMicrosoft.AspNetCore.Http;usingMicrosoft.Extensions.DependencyInjection;usingMicrosoft.Extensions.Hosting;namespaceGrpcService1

{public classStartup

{//This method gets called by the runtime. Use this method to add services to the container.//For more information on how to configure your application, visithttps://go.microsoft.com/fwlink/?LinkID=398940

public voidConfigureServices(IServiceCollection services)

{

services.AddGrpc();

}//This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

public voidConfigure(IApplicationBuilder app, IWebHostEnvironment env)

{if(env.IsDevelopment())

{

app.UseDeveloperExceptionPage();

}

app.UseRouting();

app.UseEndpoints(endpoints=>{

endpoints.MapGrpcService();

endpoints.MapGrpcService();//自己新加的服务类

endpoints.MapGet("/", async context =>{await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");

});

});

}

}

}

5.在appsettings.json文件配置http2

{"Logging": {"LogLevel": {"Default": "Information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "Information"}

},"AllowedHosts": "*","Kestrel": {"EndpointDefaults": {"Protocols": "Http2"}

}

}

然后在测试的时候需要使用临时的证书,点击确定,如果需要发布到正式环境下需要申请证书

点击运行

客户端(控制台或asp.net mvc等等):

1.安装nuget包 grpc-aspnetcore

2.将服务端的Protos文件夹整个复制到客户端

3.右键项目->编辑项目文件->将创建的.proto文件添加进去,将Server修改为Client,vs2019自动生成代码

Exe

netcoreapp3.1

4.开始愉快的使用,在项目需要的地方调用

usingGrpc.Core;usingGrpc.Net.Client;usingGrpcService1;usingSystem;namespaceConsoleApp1

{classProgram

{static async System.Threading.Tasks.Task Main(string[] args)

{var channel = GrpcChannel.ForAddress("https://localhost:5001");var client = newGreeter.GreeterClient(channel);var sayHello = client.SayHello(new HelloRequest { Name = "123"});var sayHelloAsync = await client.SayHelloAsync(new HelloRequest { Name = "123"});var client1 = newProFirst.ProFirstClient(channel);var client1SayHello = client1.SayHello(new LxpRequest { Name = "123", Age = "123"});var userInfo = client1.GetUserInfo(new LxpRequest { Name = "321", Age = "abc"});var userInfoAsync = await client1.GetUserInfoAsync(new LxpRequest { Name = "321", Age = "abc"});

Console.WriteLine("Hello World!");

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值