.netCore3.1 consul服务集群
电脑版发表于:2020/3/3 15:43
前言
Consul是一种服务网络解决方案,可跨任何运行时平台以及公共或私有云连接和保护服务
简而言之:集群
环境版本:vs2019
框架版本:.netCore 3.1
BTW:.netCore 3.1 Ocelot 支持!
实验目标如下图所示
运用 Consul
下载完后 Consul 是不需要任何安装的
通过 cmd 到当前目录执行如下命令:
consul.exe agent -dev
如下图所示:
如图可以看到网站地址为: 127.0.0.1:8500
访问该连接康康
创建 .netCore 3.1 WebApi 项目与日志建立
1. 创建项目 AiDaSi.OcDemo.ServiceInstance
2. 添加新项目 GlobleLibraryLog
3. 创建完成后双击项目名称并添加相关依赖项
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Serilog" Version="2.9.0" /> <PackageReference Include="Serilog.AspNetCore" Version="3.2.0" /> <PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" /> <PackageReference Include="Serilog.Sinks.File" Version="4.1.0" /> </ItemGroup> </Project>
4. 在此项目中创建 SerilogConfigurationLog.cs 类
public static class SerilogConfigurationLog { /// <summary> /// 创建全局Logger /// </summary> public static void InitConfig() { //日志设置 Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Console() .WriteTo.File(new CompactJsonFormatter(), Path.Combine("logs", DateTime.Now.ToString("yyyyMMddhhmmss") + ".txt")) .CreateLogger(); } }
5. 双击 AiDaSi.OcDemo.ServiceInstance 并添加相关依赖项
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Consul" Version="0.7.2.6" /> <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.1" /> <PackageReference Include="Serilog" Version="2.9.0" /> <PackageReference Include="Serilog.AspNetCore" Version="3.2.0" /> <PackageReference Include="Serilog.Extensions.Logging" Version="3.0.1" /> <PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" /> <PackageReference Include="Serilog.Sinks.File" Version="4.1.0" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\GlobleLibraryLog\GlobleLibraryLog.csproj" /> </ItemGroup> </Project>
6. 添加 Serilog 日志
修改 Program.cs
public class Program { public static void Main(string[] args) { //初始化日志系统 SerilogConfigurationLog.InitConfig(); //支持命令行参数 new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddCommandLine(args).Build(); CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging((context, loggingBuilder) => { loggingBuilder.AddFilter("Microsoft", LogLevel.Warning); loggingBuilder.AddFilter("System", LogLevel.Warning); loggingBuilder.AddSerilog(); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }).UseSerilog(); }
日志输出到 logs目录 下
注册服务到 Consul 中
1. 在项目创建文件夹 Utility 并创建 ConsulHelper.cs
2. ConsulHelper.cs 代码如下
public static class ConsulHelper { public static void ConsulRegist(this IConfiguration configuration) { //创建Consul客户端 ConsulClient client = new ConsulClient(c=> { c.Address = new Uri("http://127.0.0.1:8500/"); c.Datacenter = "dc1"; }); //重命令行中获取 ip port weight(权重) 目的是重复反向代理 string ip = configuration["ip"]; int port =int.Parse(configuration["port"]); //当为空时权重为 10 int weight = string.IsNullOrWhiteSpace(configuration["weight"]) ? 10 : int.Parse(configuration["weight"]); client.Agent.ServiceRegister(new AgentServiceRegistration() { ID = "service" + Guid.NewGuid(),//唯一的 Name = "AiDaSiService",//服务组名称 Address = ip,//ip需要改动 Port = port,//不同实例 Tags = new string[] { weight.ToString() }, //权重设置 Check = new AgentServiceCheck() //健康检测 { Interval = TimeSpan.FromSeconds(12), //每隔多久检测一次 HTTP= $"http://{ip}:{port}/api/Health/Index", //检测地址 Timeout=TimeSpan.FromSeconds(5), //多少秒为超时 DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5) //在遇到异常后关闭自身服务通道 } }); } }
ServiceRegister 参数设置
变量名称 | 变量类型 | 说明 |
---|---|---|
ID | string | 唯一的子机在服务中的名称 |
Name | string | 服务组名称 |
Address | string | 服务子机IP |
Port | int | 服务子机端口 |
Tags | string[] | 权重设置 |
Check | AgentServiceCheck | 方法方法类型说明IntervalTimeSpan?每隔多久检测一次HTTPstring检测地址TimeoutTimeSpan?多少秒为超时DeregisterCriticalServiceAfterTimeSpan?在遇到异常后关闭自身服务通道 |
从检测地址来看我们需要创建一个 HealthController.cs Api空控制器
[Route("api/[controller]")] [ApiController] public class HealthController : ControllerBase { private readonly ILogger<HealthController> _logger; private readonly IConfiguration _configuration; public HealthController(ILogger<HealthController> logger, IConfiguration configuration) { _logger = logger; _configuration = configuration; } [HttpGet] [Route("Index")] public IActionResult Index() { _logger.LogWarning($"This is HealthController {_configuration["port"]}"); return Ok(); } }
再创建一个 StudentsController Api控制器
[Route("api/[controller]")] [ApiController] public class StudentsController : ControllerBase { private readonly ILogger<StudentsController> _logger; private readonly IConfiguration _configuration; public StudentsController(ILogger<StudentsController> logger, IConfiguration configuration) { _logger = logger; _configuration = configuration; } // GET: api/Students [HttpGet] public IEnumerable<string> Get() { this._logger.LogWarning("This is StudentsController Get"); List<string> listnew = new List<string> { "Api:value1", "Api:value2", "Api:value3", "Api:value4", _configuration["port"], DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") }; return listnew; } // GET: api/Students/5 [HttpGet("{id}", Name = "Get")] public string Get(int id) { List<string> listnew = new List<string> { "Api:value1", "Api:value2", "Api:value3", "Api:value4", _configuration["port"], DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") }; return listnew[id]; } }
3. 在 Startup.cs 的 Configure 方法末尾添加 ConsulHelper.cs 应用注册
this.Configuration.ConsulRegist();
4. 通过三个 powershell 到 /bin/.netcore3.1 目录下启动三个 API
执行命令分别如下:
dotnet AiDaSi.OcDemo.ServiceInstance.dll --urls="http://*:5726" --ip="127.0.0.1" --port=5726 --weight=1 dotnet AiDaSi.OcDemo.ServiceInstance.dll --urls="http://*:5727" --ip="127.0.0.1" --port=5727 --weight=3 dotnet AiDaSi.OcDemo.ServiceInstance.dll --urls="http://*:5728" --ip="127.0.0.1" --port=5728 --weight=6
如图所示:
5. 这时我们来到127.0.0.1:8500 中看看
发现这里已经连接上了
Over