<四>引入consul
1、建立一个core库用来配置这些第三方插件
2、然后建一个consul的统一注册类,通过nuget引入nconsul.aspnetcore,grpc.aspnetcore
namespace LamiGRPC.Core.Consul
{
public static class ConsulExtentions
{
public static void AddConsulServices(this IServiceCollection services,ConfigSetting configSetting)
{
services.AddConsul(new NConsulOptions { Address = "http://localhost:8500" })
.AddGRPCHealthCheck("localhost:5000")
.RegisterService("grpctest", "localhost", 5000, new[] { "xc/grpc/test" });
}
}
}
3、新建一个库专门来存放proto文件
4、新建一个HealthCheck.proto文件用作consul的健康检查,这个不能改,直接复制就好了。
syntax = "proto3"; package grpc.health.v1; message HealthCheckRequest { string service = 1; } message HealthCheckResponse { enum ServingStatus { UNKNOWN = 0; SERVING = 1; NOT_SERVING = 2; } ServingStatus status = 1; } service Health { rpc Check(HealthCheckRequest) returns (HealthCheckResponse); rpc Watch(HealthCheckRequest) returns (stream HealthCheckResponse); }
5、使用MSBuild变量来完成proto的统一包含,我们将 csproj 项目文件中引入proto文件信息进行修改如下。
客户端使用也一样,只是把server改成 client 就好了,改完生成一下,proto文件就自动引入到服务端了
<ItemGroup> <Protobuf Include="..\LamiGRPC.Protocol\*.proto" GrpcServices="Server" Link="LamiGRPC.Protocol\%(RecursiveDir)%(Filename)%(Extension)" /> </ItemGroup>
6、实现consul的健康检查服务,这些代码不需要改复制就行了
public class HealthCheckService : Health.HealthBase { public override Task<HealthCheckResponse> Check(HealthCheckRequest request, ServerCallContext context) { //TODO:检查逻辑 return Task.FromResult(new HealthCheckResponse() { Status = HealthCheckResponse.Types.ServingStatus.Serving }); } public override async Task Watch(HealthCheckRequest request, IServerStreamWriter<HealthCheckResponse> responseStream, ServerCallContext context) { //TODO:检查逻辑 await responseStream.WriteAsync(new HealthCheckResponse() { Status = HealthCheckResponse.Types.ServingStatus.Serving }); } }
7、在startup中注册consul和服务
8、打开浏览器运行consul ui后运行我们的服务()
参考文章: ASP.NET Core 3.0 使用gRPC by 晓晨Master
ASP.NET Core gRPC 使用 Consul 服务注册发现 by 晓晨Master