zoukankan      html  css  js  c++  java
  • .Net Core Grpc Consul 实现服务注册 服务发现 负载均衡

      本文是基于..net core grpc consul 实现服务注册 服务发现 负载均衡(二)的,很多内容是直接复制过来的,..net core grpc consul 实现服务注册 服务发现 负载均衡(二)的版权属于原作者,此文的版权归属我及@蜗牛丨大神,因此,转载前请必要声明@蜗牛丨大神及本人。谢谢。

    文章内容如下:

    在上一篇 .net core grpc 实现通信(一) 中,我们实现的grpc通信在.net core中的可行性,但要在微服务中真正使用,还缺少 服务注册,服务发现及负载均衡等,本篇我们将在 .net core grpc 通信 的基础上加上 服务注册,服务发现,负载均衡。

    如对.net core grpc 通信不太熟悉的,可以看上一篇 .net core grpc 实现通信(一) ,然后再看本篇。

    grpc(https://grpc.io/)是google发布的一个开源、高性能、通用RPC(Remote Procedure Call)框架,使用HTTP/2协议,支持多路复用,并用ProtoBuf作为序列化工具,提供跨语言、跨平台支持。

    Consul(https://www.consul.io)是一个分布式,高可用、支持多数据中心的服务注册、发现、健康检查和配置共享的服务软件,由 HashiCorp 公司用 Go 语言开发。

    本次服务注册、发现 通过 Consul Api 来实现,开发过程中结合.net core 依赖注入,切面管道思想等。

    软件版本

    .net core:3.0

    grpc:1.20.1

    Consul:1.5.0

    Consul Nuget注册组件:0.7.2.6

    项目结构

    .net core 代码部分:

    Snai.GrpcClient 客户端 .net core 3.0控制台程序

    Snai.GrpcService.Hosting 服务端宿主,Api服务注册,asp.net core 3.0网站程序

    Snai.GrpcService.Impl 协议方法实现  .net standard 2.0类库

    Snai.GrpcService.Protocol 生成协议方法 .net standard 2.0类库

    Consul:(我的Windows x64版本下载下来压缩包里面只有一个consul.exe文件,可能原作者使用的是Linux版本或当时环境下的版本导致)

    conf 配置目录,本次用api注册服务,可以删除

    data 缓存数据目录,可清空里面内容

    dist Consul UI目录,本次用默认的UI,可以删除

    consul.exe 注册软件

    startup.bat 执行脚本

    项目实现

     一、服务端

    服务端主要包括Grpc服务端,Consul Api服务注册、健康检查等。

    新建Snai.GrpcService解决方案,由于这次加入了 Consul Api 服务注册,所以我们先从 Api 服务注册开始。

    1、实现 Consul Api 服务注册

    新建 Snai.GrpcService.Hosting 基于Asp.net Core 3.0空网站,在 依赖项 右击 管理NuGet程序包 浏览 找到 Consul 版本0.7.2.6安装,用于Api服务注册使用

    编辑 appsettings.json 配置文件,配置 GrpcService Grpc服务端IP和端口,HealthService健康检测名称、IP和地址,ConsulService Consul的IP和端口,代码如下

     1 {
     2   "GrpcService": {
     3     "IP": "localhost",
     4     "Port": "5031"
     5   },
     6   "HealthService": {
     7     "Name": "GrpcService",
     8     "IP": "localhost",
     9     "Port": "5021"
    10   },
    11   "ConsulService": {
    12     "IP": "localhost",
    13     "Port": "8500"
    14   },
    15   "Logging": {
    16     "LogLevel": {
    17       "Default": "Information",
    18       "Microsoft": "Warning",
    19       "Microsoft.Hosting.Lifetime": "Information"
    20     }
    21   },
    22   "AllowedHosts": "*"
    23 }

    新建Consul目录,用于放Api注册相关代码

    在Consul目录下新建Entity目录,在Entity目录下新建HealthService.cs,ConsulService.cs类,分别对应HealthService,ConsulService两个配置项,代码如下

    HealthService.cs

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Threading.Tasks;
     5 
     6 namespace Snai.GrpcService.Hosting.Consul.Entity
     7 {
     8     public class HealthService
     9     {
    10         public string Name { get; set; }
    11         public string IP { get; set; }
    12         public int Port { get; set; }
    13 
    14     }
    15 }

    ConsulService.cs

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Threading.Tasks;
     5 
     6 namespace Snai.GrpcService.Hosting.Consul.Entity
     7 {
     8     public class ConsulService
     9     {
    10         public string IP { get; set; }
    11         public int Port { get; set; }
    12     }
    13 }

    在 Consul 目录下新建 AppRregister.cs 类,添加 IApplicationBuilder 扩展方法 RegisterConsul,来调用 Consul Api 实现服务注册,代码如下

     1 using Consul;
     2 using Microsoft.AspNetCore.Builder;
     3 using Microsoft.Extensions.Hosting;
     4 using Microsoft.Extensions.Options;
     5 using Snai.GrpcService.Hosting.Consul.Entity;
     6 using System;
     7 using System.Collections.Generic;
     8 using System.Linq;
     9 using System.Threading.Tasks;
    10 
    11 namespace Snai.GrpcService.Hosting.Consul
    12 {
    13     public static class AppRregister
    14     {
    15         // 服务注册
    16         public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IHostApplicationLifetime lifetime, IOptions<HealthService> healthService, IOptions<ConsulService> consulService)
    17         {
    18             var consulClient = new ConsulClient(cfg => cfg.Address = new Uri($"http://{consulService.Value.IP}:{consulService.Value.Port}"));//请求注册的 Consul 地址
    19             var httpCheck = new AgentServiceCheck()
    20             {
    21                 DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册
    22                 Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔,或者称为心跳间隔
    23                 HTTP = $"http://{healthService.Value.IP}:{healthService.Value.Port}/health",//健康检查地址
    24                 Timeout = TimeSpan.FromSeconds(5)
    25             };
    26 
    27             // Register service with consul
    28             var registration = new AgentServiceRegistration()
    29             {
    30                 Checks = new[] { httpCheck },
    31                 ID = healthService.Value.Name + "_" + healthService.Value.Port,
    32                 Name = healthService.Value.Name,
    33                 Address = healthService.Value.IP,
    34                 Port = healthService.Value.Port,
    35                 Tags = new[] { $"urlprefix-/{healthService.Value.Name}" }//添加 urlprefix-/servicename 格式的 tag 标签,以便 Fabio 识别
    36             };
    37 
    38             consulClient.Agent.ServiceRegister(registration).Wait();//服务启动时注册,内部实现其实就是使用 Consul API 进行注册(HttpClient发起)
    39             lifetime.ApplicationStopping.Register(() =>
    40             {
    41                 consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服务停止时取消注册
    42             });
    43 
    44             return app;
    45         }
    46     }
    47 }

    修改 Startup.cs 代码

    加入 Startup(IConfiguration configuration) 构造函数,实现配置注入,如果建的是Web Api或MVC网站,默认是有的

    修改 ConfigureServices(IServiceCollection services)  方法,注册全局配置

    修改 Configure() 方法,添加健康检查路由地址 app.Map("/health", HealthMap),调用 RegisterConsul 扩展方法实现服务注册

    添加 HealthMap(IApplicationBuilder app) 实现health路由。由于只有一个健康检查地址,所以没有建Web Api网站,只建了个空网站

    代码如下,注册配置GrpcService 、 注册Rpc服务、启动Rpc服务 后面用到等下讲

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Threading.Tasks;
     5 using Microsoft.AspNetCore.Builder;
     6 using Microsoft.AspNetCore.Hosting;
     7 using Microsoft.AspNetCore.Http;
     8 using Microsoft.AspNetCore.HttpsPolicy;
     9 using Microsoft.Extensions.Configuration;
    10 using Microsoft.Extensions.DependencyInjection;
    11 using Microsoft.Extensions.Hosting;
    12 using Microsoft.Extensions.Options;
    13 using Snai.GrpcService.Hosting.Consul;
    14 using Snai.GrpcService.Hosting.Consul.Entity;
    15 
    16 namespace Snai.GrpcService.Hosting
    17 {
    18     public class Startup
    19     {
    20         public Startup(IConfiguration configuration)
    21         {
    22             Configuration = configuration;
    23         }
    24 
    25         public IConfiguration Configuration { get; }
    26 
    27         // This method gets called by the runtime. Use this method to add services to the container.
    28         public void ConfigureServices(IServiceCollection services)
    29         {
    30             //注册全局配置
    31             services.AddOptions();
    32             services.Configure<Impl.Entity.GrpcService>(Configuration.GetSection(nameof(Impl.Entity.GrpcService)));
    33             services.Configure<HealthService>(Configuration.GetSection(nameof(HealthService)));
    34             services.Configure<ConsulService>(Configuration.GetSection(nameof(ConsulService)));
    35 
    36             //注册Rpc服务
    37             services.AddSingleton<IRpcConfig, RpcConfig>();
    38         }
    39 
    40         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    41         public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime, IOptions<HealthService> healthService, IOptions<ConsulService> consulService, IRpcConfig rpc)
    42         {
    43             if (env.IsDevelopment())
    44             {
    45                 app.UseDeveloperExceptionPage();
    46             }
    47 
    48             // 添加健康检查路由地址
    49             app.Map("/health", HealthMap);
    50 
    51             // 服务注册
    52             app.RegisterConsul(lifetime, healthService, consulService);
    53 
    54             // 启动Rpc服务
    55             rpc.Start();
    56         }
    57 
    58         private static void HealthMap(IApplicationBuilder app)
    59         {
    60             app.Run(async context =>
    61             {
    62                 await context.Response.WriteAsync("OK");
    63             });
    64         }
    65     }
    66 }

    修改 Program.cs 代码,调置网站地址为 .UseUrls("http://localhost:5021"),代码如下

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Threading.Tasks;
     5 using Microsoft.AspNetCore.Hosting;
     6 using Microsoft.Extensions.Configuration;
     7 using Microsoft.Extensions.Hosting;
     8 using Microsoft.Extensions.Logging;
     9 
    10 namespace Snai.GrpcService.Hosting
    11 {
    12     public class Program
    13     {
    14         public static void Main(string[] args)
    15         {
    16             CreateHostBuilder(args).Build().Run();
    17         }
    18 
    19         public static IHostBuilder CreateHostBuilder(string[] args) =>
    20             Host.CreateDefaultBuilder(args)
    21                 .ConfigureWebHostDefaults(webBuilder =>
    22                 {
    23                     webBuilder.UseUrls("http://localhost:5021");
    24                     webBuilder.UseStartup<Startup>();
    25                 });
    26     }
    27 }

    到此 Consul Api 服务注册 已完成,最终项目结构如下:

    2、协议编写,将协议生成C#代码

    新建 Snai.GrpcService.Protocol协议类库项目,在 依赖项 右击 管理NuGet程序包 浏览 找到 Grpc.Core 版本1.20.1,Google.Protobuf 版本3.7.0,Grpc.Tools 版本1.20.1 包下载安装

    在项目根目录下新建一个 Protos文件夹并新建 msg.proto 文件,编写基于proto3语言的协议代码,用于生成各语言协议,msg.proto 代码如下

    syntax = "proto3";
    
    package Snai.GrpcService.Protocol;
    
    service MsgService{
      rpc GetSum(GetMsgNumRequest) returns (GetMsgSumReply){}
    }
    
    message GetMsgNumRequest {
      int32 Num1 = 1;
      int32 Num2 = 2;
    }
    
    message GetMsgSumReply {
      int32 Sum = 1;
    }

    编写csproj文件使项目自动生成C#代码,添加如下节点。

    1   <ItemGroup>
    2     <Protobuf Include="Protos/*.proto" OutputDir="%(RelativeDir)" CompileOutputs="false" />
    3   </ItemGroup>

    点击重新生成后,项目生成了C#代码,代码结构如下:

     3、编写协议实现代码

    新建 Snai.GrpcService.Impl 实现类库项目,在 依赖项 下载安装Grpc.Core 包,项目引用 Snai.GrpcService.Protocol

    新建 Entity 目录,在Entity目录下新建 GrpcService.cs 类,对应 Snai.GrpcService.Hosting 项目下 appsettings.json 配置文件的 GrpcService 配置项,代码如下

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Text;
     4 
     5 namespace Snai.GrpcService.Impl.Entity
     6 {
     7     public class GrpcService
     8     {
     9         public string IP { get; set; }
    10         public int Port { get; set; }
    11     }
    12 }

    在根目录下新建 RpcService 目录,在 RpcService 目录下新建 MsgServiceImpl.cs 类,继承 MsgService.MsgServiceBase 协议类,实现服务方法,代码如下

     1 using Grpc.Core;
     2 using Snai.GrpcService.Protocol;
     3 using System;
     4 using System.Collections.Generic;
     5 using System.Text;
     6 using System.Threading.Tasks;
     7 
     8 namespace Snai.GrpcService.Impl.RpcService
     9 {
    10     public class MsgServiceImpl:MsgService.MsgServiceBase
    11     {
    12         public override Task<GetMsgSumReply> GetSum(GetMsgNumRequest request, ServerCallContext context)
    13         {
    14             var result = new GetMsgSumReply();
    15 
    16             result.Sum = request.Num1 + request.Num2;
    17 
    18             Console.WriteLine(request.Num1 + "+" + request.Num2 + "=" + result.Sum);
    19 
    20             return Task.FromResult(result);
    21         }
    22     }
    23 }

    在根目录下新建IRpcConfig.cs接口,定义 Start() 用于Rpc启动基方法,代码如下

    1 using System;
    2 
    3 namespace Snai.GrpcService.Impl
    4 {
    5     public interface IRpcConfig
    6     {
    7         void Start();
    8     }
    9 }

    在根目录下新建 RpcConfig.cs 类,用于实现 IRpcConfig.cs 接口,启动Rpc服务,代码如下

     1 using Grpc.Core;
     2 using Microsoft.Extensions.Options;
     3 using Snai.GrpcService.Impl.RpcService;
     4 using Snai.GrpcService.Protocol;
     5 using System;
     6 using System.Collections.Generic;
     7 using System.Text;
     8 
     9 namespace Snai.GrpcService.Impl
    10 {
    11     public class RpcConfig : IRpcConfig
    12     {
    13         private static Server _server;
    14         private static IOptions<Entity.GrpcService> _grpcSettings;
    15 
    16         public RpcConfig(IOptions<Entity.GrpcService> grpcSettings)
    17         {
    18             _grpcSettings = grpcSettings;
    19         }
    20         public void Start()
    21         {
    22             _server = new Server
    23             {
    24                 Services = { MsgService.BindService(new MsgServiceImpl()) },
    25                 Ports = { new ServerPort(_grpcSettings.Value.IP, _grpcSettings.Value.Port, ServerCredentials.Insecure) }
    26             };
    27             _server.Start();
    28 
    29             Console.WriteLine($"Grpc ServerListening On Port {_grpcSettings.Value.Port}");
    30         }
    31     }
    32 }

    在回到Snai.GrpcService.Hosting项目中,添加对Snai.GrpcService.Impl的引用。

    在 Startup.cs 中 ConfigureServices 中注册 GrpcService 配置、注册Rpc服务,在 Configure 中 启动Rpc服务 就是上面说到的蓝色字体标识的,如图

    最终项目结构如下:

      

     到此服务端的代码实现已完成,下面我们启动Consul和服务端,验证 Api 注册和Grpc启动。

    二、Consul和服务端启动

    启动Consul,启动Grpc服务、注册服务到Consul

    1、启动Consul

    首先下载Consul:https://www.consul.io/downloads.html,本项目是Windows下进行测试,下载相应压缩包得到consul.exe

    由于本次用Api注册,用Consul默认自带UI,所以conf和dist可删除(我的压缩包里面只有consul.exe

    清除Consul/data 内容,新建startup.bat文件,输入下面代码,双击启动Consul,本项目测试时一台机器,所以把 本机IP 改成 127.0.0.1

    consul agent -server -datacenter=grpc-consul -bootstrap -data-dir ./data -ui -node=grpc-consul1 -bind 本机IP -client=0.0.0.0

     

    再在Consul目录下启动另一个cmd命令行窗口,输入命令:consul operator raft list-peers 查看状态查看状态,结果如下

    输入http://localhost:8500 打开Consul UI查看情况

    Consul 启动成功。

    在 .net core Ocelot Consul 实现API网关 服务注册 服务发现 负载均衡 中后面 Consul 部分,有 Consul 集群搭建等其他介绍,可以去参考看下。

    2、启动服务端,启动Grpc服务、注册服务到Consul

    由于客户端要实现负载,所以把 Snai.GrpcService.Hosting 项目生成两次,启动两个一样的服务端,只是端口不同

    服务5021 地址为5021: .UseUrls("http://localhost:5021"),GrpcService:5031,如下图

     

    启动 服务5021和服务5022两个服务端,如下面

     看到 Grpc ServerListening On Port 5031,Grpc ServerListening On Port 5032 说明 Grpc 服务端启动成功

    打开Consul服务查看地址  http://localhost:8500/ui/grpc-consul/services 查看,两个GrpcService注册成功,健康检查状态正常

    到此,Grpc启动正常,Consul Api服务注册、健康检查都正常,下面开始实现Grpc客户端

    三、客户端

    客户端主要包括Grpc客户端,Consul Api服务发现、负载均衡等。

    新建Snai.GrpcClient 控制台程序,在 依赖项 下载安装Grpc.Core 包,项目引用Snai.GrpcService.Protocol,在依赖项下载安装下面工具组件包

    用于读取 json配置:Microsoft.Extensions.Configuration,Microsoft.Extensions.Configuration.Json 

    用于依赖注入:Microsoft.Extensions.DependencyInjection

    用于注入全局配置:Microsoft.Extensions.Options,Microsoft.Extensions.Options.ConfigurationExtensions

    在项目根目录下新建 Utils 目录,在 Utils 目录下新建 HttpHelper.cs 类,用于程序内发送http请求,代码如下

      1 using System;
      2 using System.Collections.Generic;
      3 using System.Net.Http;
      4 using System.Text;
      5 using System.Threading.Tasks;
      6 
      7 /// <summary>
      8 /// 参考 pudefu https://www.cnblogs.com/pudefu/p/7581956.html ,在此表示感谢
      9 /// </summary>
     10 namespace Snai.GrpcClient.Utils
     11 {
     12     public class HttpHelper
     13     {
     14         /// <summary>
     15         /// 同步GET请求
     16         /// </summary>
     17         /// <param name="url"></param>
     18         /// <param name="headers"></param>
     19         /// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
     20         /// <returns></returns>
     21         public static string HttpGet(string url, Dictionary<string, string> headers = null, int timeout = 0)
     22         {
     23             using (HttpClient client = new HttpClient())
     24             {
     25                 if (headers != null)
     26                 {
     27                     foreach (KeyValuePair<string, string> header in headers)
     28                     {
     29                         client.DefaultRequestHeaders.Add(header.Key, header.Value);
     30                     }
     31                 }
     32                 if (timeout > 0)
     33                 {
     34                     client.Timeout = new TimeSpan(0, 0, timeout);
     35                 }
     36                 Byte[] resultBytes = client.GetByteArrayAsync(url).Result;
     37                 return Encoding.UTF8.GetString(resultBytes);
     38             }
     39         }
     40 
     41         /// <summary>
     42         /// 异步GET请求
     43         /// </summary>
     44         /// <param name="url"></param>
     45         /// <param name="headers"></param>
     46         /// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
     47         /// <returns></returns>
     48         public static async Task<string> HttpGetAsync(string url, Dictionary<string, string> headers = null, int timeout = 0)
     49         {
     50             using (HttpClient client = new HttpClient())
     51             {
     52                 if (headers != null)
     53                 {
     54                     foreach (KeyValuePair<string, string> header in headers)
     55                     {
     56                         client.DefaultRequestHeaders.Add(header.Key, header.Value);
     57                     }
     58                 }
     59                 if (timeout > 0)
     60                 {
     61                     client.Timeout = new TimeSpan(0, 0, timeout);
     62                 }
     63                 Byte[] resultBytes = await client.GetByteArrayAsync(url);
     64                 return Encoding.Default.GetString(resultBytes);
     65             }
     66         }
     67 
     68 
     69         /// <summary>
     70         /// 同步POST请求
     71         /// </summary>
     72         /// <param name="url"></param>
     73         /// <param name="postData"></param>
     74         /// <param name="headers"></param>
     75         /// <param name="contentType"></param>
     76         /// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
     77         /// <param name="encoding">默认UTF8</param>
     78         /// <returns></returns>
     79         public static string HttpPost(string url, string postData, Dictionary<string, string> headers = null, string contentType = null, int timeout = 0, Encoding encoding = null)
     80         {
     81             using (HttpClient client = new HttpClient())
     82             {
     83                 if (headers != null)
     84                 {
     85                     foreach (KeyValuePair<string, string> header in headers)
     86                     {
     87                         client.DefaultRequestHeaders.Add(header.Key, header.Value);
     88                     }
     89                 }
     90                 if (timeout > 0)
     91                 {
     92                     client.Timeout = new TimeSpan(0, 0, timeout);
     93                 }
     94                 using (HttpContent content = new StringContent(postData ?? "", encoding ?? Encoding.UTF8))
     95                 {
     96                     if (contentType != null)
     97                     {
     98                         content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
     99                     }
    100                     using (HttpResponseMessage responseMessage = client.PostAsync(url, content).Result)
    101                     {
    102                         Byte[] resultBytes = responseMessage.Content.ReadAsByteArrayAsync().Result;
    103                         return Encoding.UTF8.GetString(resultBytes);
    104                     }
    105                 }
    106             }
    107         }
    108 
    109         /// <summary>
    110         /// 异步POST请求
    111         /// </summary>
    112         /// <param name="url"></param>
    113         /// <param name="postData"></param>
    114         /// <param name="headers"></param>
    115         /// <param name="contentType"></param>
    116         /// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
    117         /// <param name="encoding">默认UTF8</param>
    118         /// <returns></returns>
    119         public static async Task<string> HttpPostAsync(string url, string postData, Dictionary<string, string> headers = null, string contentType = null, int timeout = 0, Encoding encoding = null)
    120         {
    121             using (HttpClient client = new HttpClient())
    122             {
    123                 if (headers != null)
    124                 {
    125                     foreach (KeyValuePair<string, string> header in headers)
    126                     {
    127                         client.DefaultRequestHeaders.Add(header.Key, header.Value);
    128                     }
    129                 }
    130                 if (timeout > 0)
    131                 {
    132                     client.Timeout = new TimeSpan(0, 0, timeout);
    133                 }
    134                 using (HttpContent content = new StringContent(postData ?? "", encoding ?? Encoding.UTF8))
    135                 {
    136                     if (contentType != null)
    137                     {
    138                         content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
    139                     }
    140                     using (HttpResponseMessage responseMessage = await client.PostAsync(url, content))
    141                     {
    142                         Byte[] resultBytes = await responseMessage.Content.ReadAsByteArrayAsync();
    143                         return Encoding.UTF8.GetString(resultBytes);
    144                     }
    145                 }
    146             }
    147         }
    148     }
    149 }

    在项目根目录下新建 Consul 目录,在 Consul 目录下新建 Entity 目录,在 Entity 目录下新建 HealthCheck.cs 类,用于接收 Consul Api发现的信息实体,代码如下

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Text;
     4 
     5 namespace Snai.GrpcClient.Consul.Entity
     6 {
     7     public class HealthCheck
     8     {
     9         public string Node { get; set; }
    10         public string CheckID { get; set; }
    11         public string Name { get; set; }
    12         public string Status { get; set; }
    13         public string Notes { get; set; }
    14         public string Output { get; set; }
    15         public string ServiceID { get; set; }
    16         public string ServiceName { get; set; }
    17         public string[] ServiceTags { get; set; }
    18         public dynamic Definition { get; set; }
    19         public int CreateIndex { get; set; }
    20         public int ModifyIndex { get; set; }
    21     }
    22 }

     在项目根目录下新建 Framework 目录,在 Framework 目录下新建 Entity 目录,在 Entity 目录下新建 ConsulService.cs 和 GrpcServiceSettings.cs 类,分别对应配置appsettings.json的 ConsulService,GrpcServiceSettings 两个配置项,代码如下

    ConsulService.cs

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Text;
     4 
     5 namespace Snai.GrpcClient.Framework.Entity
     6 {
     7     public class ConsulService
     8     {
     9         public string IP { get; set; }
    10         public int Port { get; set; }
    11     }
    12 }

     GrpcServiceSettings.cs

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Text;
     4 
     5 namespace Snai.GrpcClient.Framework.Entity
     6 {
     7     public class GrpcServiceSettings
     8     {
     9         public List<GrpcService> GrpcServices { get; set; }
    10     }
    11     public class GrpcService
    12     {
    13         public string ServiceName { get; set; }
    14         public string ServiceID { get; set; }
    15         public string IP { get; set; }
    16         public int Port { get; set; }
    17         public int Weight { get; set; }
    18     }
    19 }

    在 Consul 目录下新建 IAppFind.cs 接口,定义 FindConsul() 用于 Consul 服务发现基方法,代码如下

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Text;
     4 
     5 namespace Snai.GrpcClient.Consul
     6 {
     7     public interface IAppFind
     8     {
     9         IEnumerable<string> FindConsul(string ServiceName);
    10     }
    11 }

    在 Consul 目录下新建 AppFind.cs 类,用于实现 IAppFind.cs 接口,实现 Consul 服务发现方法,代码如下

     1 using Microsoft.Extensions.Options;
     2 using Newtonsoft.Json;
     3 using Snai.GrpcClient.Consul.Entity;
     4 using Snai.GrpcClient.Framework.Entity;
     5 using Snai.GrpcClient.Utils;
     6 using System;
     7 using System.Collections.Generic;
     8 using System.Linq;
     9 using System.Text;
    10 
    11 namespace Snai.GrpcClient.Consul
    12 {
    13     /// <summary>
    14     /// 服务发现
    15     /// (服务和健康信息)http://localhost:8500/v1/health/service/GrpcService
    16     /// (健康信息)http://localhost:8500/v1/health/checks/GrpcService
    17     /// </summary>
    18     public class AppFind : IAppFind
    19     {
    20         private static IOptions<GrpcServiceSettings> _grpcSettings;
    21         private static IOptions<ConsulService> _consulSettings;
    22         public AppFind(IOptions<GrpcServiceSettings> grpcSettings, IOptions<ConsulService> consulSettings)
    23         {
    24             _grpcSettings = grpcSettings;
    25             _consulSettings = consulSettings;
    26         }
    27         public IEnumerable<string> FindConsul(string ServiceName)
    28         {
    29             Dictionary<string, string> headers = new Dictionary<string, string>();
    30 
    31             var consul = _consulSettings.Value;
    32             string findUrl = $"http://{consul.IP}:{consul.Port}/v1/health/checks/{ServiceName}";
    33 
    34             string findResult = HttpHelper.HttpGet(findUrl, headers, 5);
    35             if (findResult.Equals(""))
    36             {
    37                 var grpcServices = _grpcSettings.Value.GrpcServices;
    38                 return grpcServices.Where(g => g.ServiceName.Equals(ServiceName, StringComparison.CurrentCultureIgnoreCase)).Select(s => s.ServiceID);
    39             }
    40 
    41             var findCheck = JsonConvert.DeserializeObject<List<HealthCheck>>(findResult);
    42 
    43             return findCheck.Where(g => g.Status.Equals("passing", StringComparison.CurrentCultureIgnoreCase)).Select(g => g.ServiceID);
    44         }
    45     }
    46 }

    在项目根目录下新建 LoadBalance 目录,在 LoadBalance 目录下新建 ILoadBalance.cs 接口,定义 GetGrpcService() 用于负载均衡基方法,代码如下

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Text;
     4 
     5 namespace Snai.GrpcClient.LoadBalance
     6 {
     7     public interface ILoadBalance
     8     {
     9         string GetGrpcService(string ServiceName);
    10     }
    11 }

    在 LoadBalance 目录下新建 WeightRoundBalance.cs 类,用于实现 ILoadBalance.cs 接口,实现 GetGrpcService() 负载均衡方法,本次负载均衡实现权重轮询算法,代码如下

     1 using Microsoft.Extensions.Options;
     2 using Snai.GrpcClient.Consul;
     3 using Snai.GrpcClient.Framework.Entity;
     4 using System;
     5 using System.Collections.Generic;
     6 using System.Linq;
     7 using System.Text;
     8 
     9 namespace Snai.GrpcClient.LoadBalance
    10 {
    11     /// <summary>
    12     /// 权重轮询
    13     /// </summary>
    14     public class WeightRoundBalance: ILoadBalance
    15     {
    16         int Balance;
    17         IOptions<GrpcServiceSettings> GrpcSettings;
    18         IAppFind AppFind;
    19 
    20         public WeightRoundBalance(IOptions<GrpcServiceSettings> grpcSettings, IAppFind appFind)
    21         {
    22             Balance = 0;
    23             GrpcSettings = grpcSettings;
    24             AppFind = appFind;
    25         }
    26 
    27         public string GetGrpcService(string ServiceName)
    28         {
    29             var grpcServices = GrpcSettings.Value.GrpcServices;
    30 
    31             var healthServiceID = AppFind.FindConsul(ServiceName);
    32 
    33             if (grpcServices == null || grpcServices.Count() == 0 || healthServiceID == null || healthServiceID.Count() == 0)
    34             {
    35                 return "";
    36             }
    37 
    38             //健康的服务
    39             var healthServices = new List<Framework.Entity.GrpcService>();
    40 
    41             foreach (var service in grpcServices)
    42             {
    43                 foreach (var health in healthServiceID)
    44                 {
    45                     if (service.ServiceID.Equals(health, StringComparison.CurrentCultureIgnoreCase))
    46                     {
    47                         healthServices.Add(service);
    48                         break;
    49                     }
    50                 }
    51             }
    52 
    53             if (healthServices == null || healthServices.Count() == 0)
    54             {
    55                 return "";
    56             }
    57 
    58             //加权轮询
    59             var services = new List<string>();
    60 
    61             foreach (var service in healthServices)
    62             {
    63                 services.AddRange(Enumerable.Repeat(service.IP + ":" + service.Port, service.Weight));
    64             }
    65 
    66             var servicesArray = services.ToArray();
    67 
    68             Balance = Balance % servicesArray.Length;
    69             var grpcUrl = servicesArray[Balance];
    70             Balance = Balance + 1;
    71 
    72             return grpcUrl;
    73         }
    74     }
    75 }

    在项目根目录下新建 RpcClient 目录,在 RpcClient 目录下新建 IMsgClient.cs 接口,定义 GetSum() 用于Grpc客户端调用基方法,代码如下

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Text;
     4 
     5 namespace Snai.GrpcClient.RpcClient
     6 {
     7     public interface IMsgClient
     8     {
     9         void GetSum(int num1, int num2);
    10     }
    11 }

    在 RpcClient 目录下新建 MsgClient.cs 类,用于实现 IMsgClient.cs 接口,实现 GetSum() 方法用于Grpc客户端调用,代码如下

     1 using Grpc.Core;
     2 using Snai.GrpcClient.LoadBalance;
     3 using Snai.GrpcService.Protocol;
     4 using System;
     5 using System.Collections.Generic;
     6 using System.Text;
     7 
     8 namespace Snai.GrpcClient.RpcClient
     9 {
    10     public class MsgClient:IMsgClient
    11     {
    12         ILoadBalance LoadBalance;
    13         Channel GrpcChannel;
    14         MsgService.MsgServiceClient GrpcClient;
    15 
    16         public MsgClient(ILoadBalance loadBalance)
    17         {
    18             LoadBalance = loadBalance;
    19 
    20             var grpcUrl = LoadBalance.GetGrpcService("GrpcService");
    21 
    22             if (!grpcUrl.Equals(""))
    23             {
    24                 Console.WriteLine($"Grpc Service:{grpcUrl}");
    25 
    26                 GrpcChannel = new Channel(grpcUrl, ChannelCredentials.Insecure);
    27                 GrpcClient = new MsgService.MsgServiceClient(GrpcChannel);
    28             }
    29         }
    30 
    31         public void GetSum(int num1, int num2)
    32         {
    33             if (GrpcClient != null)
    34             {
    35                 GetMsgSumReply msgSum = GrpcClient.GetSum(new GetMsgNumRequest
    36                 {
    37                     Num1 = num1,
    38                     Num2 = num2
    39                 });
    40 
    41                 Console.WriteLine("Grpc Client Call GetSum():" + msgSum.Sum);
    42             }
    43             else
    44             {
    45                 Console.WriteLine("所有负载都挂掉了!");
    46             }
    47         }
    48     }
    49 }

    在 Framework 目录下新建 DependencyInitialize.cs 类,定义 AddImplement() 方法用于注册全局配置和类到容器,实现依赖注入,代码如下

     1 using Microsoft.Extensions.Configuration;
     2 using Microsoft.Extensions.DependencyInjection;
     3 using Snai.GrpcClient.Consul;
     4 using Snai.GrpcClient.Framework.Entity;
     5 using Snai.GrpcClient.LoadBalance;
     6 using Snai.GrpcClient.RpcClient;
     7 using System;
     8 using System.Collections.Generic;
     9 using System.IO;
    10 using System.Text;
    11 
    12 namespace Snai.GrpcClient.Framework
    13 {
    14     /// <summary>
    15     /// IServiceCollection 依赖注入生命周期
    16     /// AddTransient 每次都是全新的
    17     /// AddScoped    在一个范围之内只有同一个实例(同一个线程,同一个浏览器请求只有一个实例)
    18     /// AddSingleton 单例
    19     /// </summary>
    20     public static class DependencyInitialize
    21     {
    22         /// <summary>
    23         /// 注册对象
    24         /// </summary>
    25         /// <param name="services">The services.</param>
    26         /*
    27          * IAppFind AppFind;
    28          * 构造函数注入使用 IAppFind appFind
    29          * AppFind = appFind;
    30          */
    31         public static void AddImplement(this IServiceCollection services)
    32         {
    33             //添加 json 文件路径
    34             var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
    35             //创建配置根对象
    36             var configurationRoot = builder.Build();
    37 
    38             //注册全局配置
    39             services.AddConfigImplement(configurationRoot);
    40 
    41             //注册服务发现
    42             services.AddScoped<IAppFind, AppFind>();
    43 
    44             //注册负载均衡
    45             if (configurationRoot["LoadBalancer"].Equals("WeightRound", StringComparison.CurrentCultureIgnoreCase))
    46             {
    47                 services.AddSingleton<ILoadBalance, WeightRoundBalance>();
    48             }
    49 
    50             //注册Rpc客户端
    51             services.AddTransient<IMsgClient, MsgClient>();
    52         }
    53 
    54         /// <summary>
    55         /// 注册全局配置
    56         /// </summary>
    57         /// <param name="services">The services.</param>
    58         /// <param name="configurationRoot">The configurationRoot.</param>
    59         /*  
    60          *  IOptions<GrpcServiceSettings> GrpcSettings;
    61          *  构造函数注入使用 IOptions<GrpcServiceSettings> grpcSettings
    62          *  GrpcSettings = grpcSettings;
    63          */
    64         public static void AddConfigImplement(this IServiceCollection services, IConfigurationRoot configurationRoot)
    65         {
    66             //注册配置对象
    67             services.AddOptions();
    68             services.Configure<GrpcServiceSettings>(configurationRoot.GetSection(nameof(GrpcServiceSettings)));
    69             services.Configure<ConsulService>(configurationRoot.GetSection(nameof(ConsulService)));
    70         }
    71     }
    72 }

      在根目录下新建 appsettings.json 配置文件,配置 GrpcServiceSettings 的 GrpcServices 为服务端发布的两个服务5021和5022,LoadBalancer 负载均衡为 WeightRound 权重轮询(如实现其他负载方法可做相应配置,注册负载均衡时也做相应修改),ConsulService Consul的IP和端口,代码如下

     1 {
     2   "GrpcServiceSettings": {
     3     "GrpcServices": [
     4       {
     5         "ServiceName": "GrpcService",
     6         "ServiceID": "GrpcService_5021",
     7         "IP": "localhost",
     8         "Port": "5031",
     9         "Weight": "2"
    10       },
    11       {
    12         "ServiceName": "GrpcService",
    13         "ServiceID": "GrpcService_5022",
    14         "IP": "localhost",
    15         "Port": "5032",
    16         "Weight": "1"
    17       }
    18     ]
    19   },
    20   "LoadBalancer": "WeightRound",
    21   "ConsulService": {
    22     "IP": "localhost",
    23     "Port": "8500"
    24   }
    25 }

    GrpcServices Grpc服务列表

      ServiceName:服务名称,负载同一服务名称相同

      ServiceID:服务ID,保持唯一

      IP:服务IP

      Port:端口

      Weight:服务权重

     修改 Program.cs 的 Main() 方法,调用 AddImplement(),注册全局配置和类到容器,注入使用 MsgClient 类的 GetSum() 方法,实现 Grpc 调用,代码如下

     1 using Microsoft.Extensions.DependencyInjection;
     2 using Snai.GrpcClient.Framework;
     3 using Snai.GrpcClient.RpcClient;
     4 using System;
     5 
     6 namespace Snai.GrpcClient
     7 {
     8     class Program
     9     {
    10         static void Main(string[] args)
    11         {
    12             IServiceCollection service = new ServiceCollection();
    13 
    14             //注册对象
    15             service.AddImplement();
    16 
    17             //注入使用对象
    18             var provider = service.BuildServiceProvider();
    19 
    20             string exeArg = string.Empty;
    21             Console.WriteLine("Grpc调用!");
    22             Console.WriteLine("-c	调用Grpc服务;");
    23             Console.WriteLine("-q	退出服务;");
    24 
    25             while (true)
    26             {
    27                 exeArg = Console.ReadKey().KeyChar.ToString();
    28                 Console.WriteLine();
    29 
    30                 if (exeArg.ToLower().Equals("c", StringComparison.CurrentCultureIgnoreCase))
    31                 {
    32                     //调用服务
    33                     var rpcClient = provider.GetService<IMsgClient>();
    34                     rpcClient.GetSum(10, 2);
    35                 }
    36                 else if (exeArg.ToLower().Equals("q", StringComparison.CurrentCultureIgnoreCase))
    37                 {
    38                     break;
    39                 }
    40                 else
    41                 {
    42                     Console.WriteLine("参数异常!");
    43                 }
    44             }
    45         }
    46     }
    47 }

    右击项目生成,最终项目结构如下:

    到此客户端的代码实现已完成,下面运行测试 Grpc+Consul 服务注册、服务发现和负载均衡。

    四、运行测试 Grpc+Consul 服务注册、服务发现和负载均衡

     双击 startup.bat 启动 Consul,再启动服务5021和5022,启动成功打开 http://localhost:8500/ui/#/grpc-consul/services/GrpcService 查看服务情况

    启动 Snai.GrpcClient 客户端

    输入 c 调用Grpc服务,调用3次,5031调用2次,5032调用1次,成功实现负载均衡

    关掉服务5022,等10秒左右(因为设置健康检查时间间隔10秒),再输入 c 调用Grpc服务,只调用5031

    打开 http://localhost:8500/ui/#/grpc-consul/services/GrpcService 查看,5022 状态失败,或消失

    Grpc+Consul实现服务注册、服务发现、健康检查和负载均衡已完成

    源码访问地址:https://github.com/Liu-Alan/Grpc-Consul

  • 相关阅读:
    Linux vim的四中模式
    Linux 打包压缩解压缩
    Linux 写入查看文本
    Linux 文件复制和移动
    Linux 创建删除目录
    Linux cd命令
    vim 文本替换
    linux工作中使用命令
    is 和 == 的区别
    再次复习python
  • 原文地址:https://www.cnblogs.com/fanqisoft/p/10861667.html
Copyright © 2011-2022 走看看