服务端:
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!");
}
}
}