tnblog
首页
视频
资源
登录

.netCore3.1 consul服务集群

9048人阅读 2020/3/3 15:43 总访问:3667436 评论:1 收藏:0 手机
分类: .net后台框架

前言


Consul是一种服务网络解决方案,可跨任何运行时平台以及公共或私有云连接和保护服务

简而言之:集群


下载地址



环境版本:vs2019 

框架版本:.netCore 3.1

BTW:.netCore 3.1 Ocelot 支持!


实验目标如下图所示




运用 Consul


下载完后 Consul 是不需要任何安装的


通过 cmd 到当前目录执行如下命令:

  1. consul.exe agent -dev


如下图所示:


如图可以看到网站地址为: 127.0.0.1:8500

访问该连接康康




创建 .netCore 3.1 WebApi 项目与日志建立


1. 创建项目 AiDaSi.OcDemo.ServiceInstance



2. 添加新项目 GlobleLibraryLog



3. 创建完成后双击项目名称并添加相关依赖项

  1. <Project Sdk="Microsoft.NET.Sdk">
  2.   <PropertyGroup>
  3.     <TargetFramework>netcoreapp3.1</TargetFramework>
  4.   </PropertyGroup>
  5.   <ItemGroup>
  6.     <PackageReference Include="Serilog" Version="2.9.0" />
  7.     <PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
  8.     <PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
  9.     <PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />
  10.   </ItemGroup>
  11. </Project>


4. 在此项目中创建 SerilogConfigurationLog.cs

  1. public static class SerilogConfigurationLog
  2. {
  3.     /// <summary>
  4.     /// 创建全局Logger
  5.     /// </summary>
  6.     public static void InitConfig()
  7.     {
  8.         //日志设置
  9.         Log.Logger = new LoggerConfiguration()
  10.                        .MinimumLevel.Debug()
  11.                        .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Information)
  12.                        .Enrich.FromLogContext()
  13.                        .WriteTo.Console()
  14.                        .WriteTo.File(new CompactJsonFormatter(), Path.Combine("logs", DateTime.Now.ToString("yyyyMMddhhmmss") + ".txt"))
  15.                        .CreateLogger();
  16.     }
  17. }



5. 双击 AiDaSi.OcDemo.ServiceInstance 并添加相关依赖项


  1. <Project Sdk="Microsoft.NET.Sdk.Web">
  2.   <PropertyGroup>
  3.     <TargetFramework>netcoreapp3.1</TargetFramework>
  4.   </PropertyGroup>
  5.   <ItemGroup>
  6.     <PackageReference Include="Consul" Version="0.7.2.6" />
  7.     <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.1" />
  8.     <PackageReference Include="Serilog" Version="2.9.0" />
  9.     <PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
  10.     <PackageReference Include="Serilog.Extensions.Logging" Version="3.0.1" />
  11.     <PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
  12.     <PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />
  13.   </ItemGroup>
  14.   <ItemGroup>
  15.     <ProjectReference Include="..\GlobleLibraryLog\GlobleLibraryLog.csproj" />
  16.   </ItemGroup>
  17. </Project>


6. 添加 Serilog 日志 


修改 Program.cs  

  1. public class Program
  2. {
  3.     public static void Main(string[] args)
  4.     {
  5.         //初始化日志系统
  6.         SerilogConfigurationLog.InitConfig();
  7.         //支持命令行参数
  8.         new ConfigurationBuilder()
  9.             .SetBasePath(Directory.GetCurrentDirectory())
  10.             .AddCommandLine(args).Build();
  11.         CreateHostBuilder(args).Build().Run();
  12.     }
  13.     public static IHostBuilder CreateHostBuilder(string[] args) =>
  14.         Host.CreateDefaultBuilder(args)
  15.         .ConfigureLogging((context, loggingBuilder) => {
  16.             loggingBuilder.AddFilter("Microsoft", LogLevel.Warning);
  17.             loggingBuilder.AddFilter("System", LogLevel.Warning);
  18.             loggingBuilder.AddSerilog();
  19.         })
  20.             .ConfigureWebHostDefaults(webBuilder =>
  21.             {
  22.                 webBuilder.UseStartup<Startup>();
  23.             }).UseSerilog();
  24. }


日志输出到 logs目录


注册服务到 Consul 中 


1. 在项目创建文件夹 Utility 并创建 ConsulHelper.cs


2. ConsulHelper.cs 代码如下

  1. public static class ConsulHelper
  2. {
  3.     public static void ConsulRegist(this IConfiguration configuration) 
  4.     {
  5.         //创建Consul客户端
  6.         ConsulClient client = new ConsulClient(c=> {
  7.             c.Address = new Uri("http://127.0.0.1:8500/");
  8.             c.Datacenter = "dc1";
  9.         });
  10.         //重命令行中获取 ip port weight(权重) 目的是重复反向代理
  11.         string ip = configuration["ip"];
  12.         int port =int.Parse(configuration["port"]);
  13.         //当为空时权重为 10
  14.         int weight = string.IsNullOrWhiteSpace(configuration["weight"]) ? 10 : int.Parse(configuration["weight"]);
  15.         client.Agent.ServiceRegister(new AgentServiceRegistration()
  16.         {
  17.             ID = "service" + Guid.NewGuid(),//唯一的
  18.             Name = "AiDaSiService",//服务组名称
  19.             Address = ip,//ip需要改动
  20.             Port = port,//不同实例
  21.             Tags = new string[] { weight.ToString() }, //权重设置
  22.             Check = new AgentServiceCheck() //健康检测
  23.             {
  24.                 Interval = TimeSpan.FromSeconds(12), //每隔多久检测一次
  25.                 HTTP= $"http://{ip}:{port}/api/Health/Index"//检测地址
  26.                 Timeout=TimeSpan.FromSeconds(5), //多少秒为超时
  27.                 DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5//在遇到异常后关闭自身服务通道
  28.             }
  29.         });
  30.     }
  31. }


ServiceRegister 参数设置

变量名称变量类型说明
IDstring唯一的子机在服务中的名称
Namestring服务组名称
Addressstring服务子机IP
Portint服务子机端口
Tagsstring[]权重设置
CheckAgentServiceCheck方法方法类型说明IntervalTimeSpan?每隔多久检测一次HTTPstring检测地址TimeoutTimeSpan?多少秒为超时DeregisterCriticalServiceAfterTimeSpan?在遇到异常后关闭自身服务通道


从检测地址来看我们需要创建一个 HealthController.cs Api空控制器

  1. [Route("api/[controller]")]
  2. [ApiController]
  3. public class HealthController : ControllerBase
  4. {
  5.     private readonly ILogger<HealthController> _logger;
  6.     private readonly IConfiguration _configuration;
  7.     public HealthController(ILogger<HealthController> logger, IConfiguration configuration)
  8.     {
  9.         _logger = logger;
  10.         _configuration = configuration;
  11.     }
  12.     [HttpGet]
  13.     [Route("Index")]
  14.     public IActionResult Index() 
  15.     {
  16.         _logger.LogWarning($"This is HealthController {_configuration["port"]}");
  17.         return Ok();
  18.     }
  19. }


再创建一个 StudentsController Api控制器

  1. [Route("api/[controller]")]
  2. [ApiController]
  3. public class StudentsController : ControllerBase
  4. {
  5.     private readonly ILogger<StudentsController> _logger;
  6.     private readonly IConfiguration _configuration;
  7.     public StudentsController(ILogger<StudentsController> logger, IConfiguration configuration)
  8.     {
  9.         _logger = logger;
  10.         _configuration = configuration;
  11.     }
  12.     // GET: api/Students
  13.     [HttpGet]
  14.     public IEnumerable<stringGet()
  15.     {
  16.         this._logger.LogWarning("This is StudentsController Get");
  17.         List<string> listnew = new List<string>
  18.         {
  19.             "Api:value1",
  20.             "Api:value2",
  21.             "Api:value3",
  22.             "Api:value4",
  23.            _configuration["port"],
  24.             DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")
  25.         };
  26.         return listnew;
  27.     }
  28.     // GET: api/Students/5
  29.     [HttpGet("{id}", Name = "Get")]
  30.     public string Get(int id)
  31.     {
  32.         List<string> listnew = new List<string>
  33.         {
  34.             "Api:value1",
  35.             "Api:value2",
  36.             "Api:value3",
  37.             "Api:value4",
  38.            _configuration["port"],
  39.             DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")
  40.         };
  41.         return listnew[id];
  42.     }
  43. }




3. 在 Startup.cs 的 Configure 方法末尾添加 ConsulHelper.cs 应用注册 

  1. this.Configuration.ConsulRegist();


4. 通过三个 powershell/bin/.netcore3.1 目录下启动三个 API


执行命令分别如下:

  1. dotnet AiDaSi.OcDemo.ServiceInstance.dll --urls="http://*:5726" --ip="127.0.0.1" --port=5726 --weight=1
  2. dotnet AiDaSi.OcDemo.ServiceInstance.dll --urls="http://*:5727" --ip="127.0.0.1" --port=5727 --weight=3
  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













欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739

评价

剑轩

2020/5/27 20:38:23

哈哈,我最近准备上这个,来看看

consul实现简单的服务集群,负载均衡调用

接上一篇,consul要实现简单的服务集群,其实也很简单,只需要把多个服务使用统一个名字注入即可,然后调用的时候通过服务...

net core 使用 EF Code First

下面这些内容很老了看这篇:https://www.tnblog.net/aojiancc2/article/details/5365 项目使用多层,把数据库访问...

.net mvc分部页,.net core分部页

.net分部页的三种方式第一种:@Html.Partial(&quot;_分部页&quot;)第二种:@{ Html.RenderPartial(&quot;分部页&quot;);}...

StackExchange.Redis操作redis(net core支持)

官方git开源地址https://github.com/StackExchange/StackExchange.Redis官方文档在docs里边都是官方的文档通过nuget命令下...

.net core 使用session

tip:net core 2.2后可以直接启用session了,不用在自己添加一次session依赖,本身就添加了使用nuget添加引用Microsoft.AspN...

通俗易懂,什么是.net?什么是.net Framework?什么是.net core?

朋友圈@蓝羽 看到一篇文章写的太详细太通俗了,搬过来细细看完,保证你对.NET有个新的认识理解原文地址:https://www.cnblo...

asp.net core2.0 依赖注入 AddTransient与AddScoped的区别

asp.net core主要提供了三种依赖注入的方式其中AddTransient与AddSingleton比较好区别AddTransient瞬时模式:每次都获取一...

.net core 使用 Kestrel

Kestrel介绍 Kestrel是一个基于libuv的跨平台web服务器 在.net core项目中就可以不一定要发布在iis下面了Kestrel体验可以使...

net core中使用cookie

net core中可以使用传统的cookie也可以使用加密的cookieNET CORE中使用传统cookie设置:HttpContext.Response.Cookies.Appe...

net core项目结构简单分析

一:wwwrootwwwroot用于存放网站的静态资源,例如css,js,图片与相关的前端插件等lib主要是第三方的插件,例如微软默认引用...

net core使用EF之DB First

一.新建一个.net core的MVC项目新建好项目后,不能像以前一样直接在新建项中添加ef了,需要用命令在添加ef的依赖二.使用Nug...

.net core使用requestresponse下载文件下载excel等

使用request获取内容net core中request没有直接的索引方法,需要点里边的Query,或者formstringbase64=Request.Form[&quot;f...

iframe自适应高度与配合net core使用

去掉iframe边框frameborder=&quot;0&quot;去掉滚动条scrolling=&quot;no&quot;iframe 自适应高度如果内容是固定的,那么就...

net core启动报错Unable to configure HTTPS endpoint. No server certificate was specified

这是因为net core2.1默认使用的https,如果使用Kestrel web服务器的话没有安装证书就会报这个错其实仔细看他的错误提示,其...

net core中使用url编码与解码操作

net core中暂时还没有以前asp.net与mvc中的server对象。获取url的编码与解码操作不能使用以前的server对象来获取。使用的是...
这一世以无限游戏为使命!
排名
2
文章
657
粉丝
44
评论
93
docker中Sware集群与service
尘叶心繁 : 想学呀!我教你呀
一个bug让程序员走上法庭 索赔金额达400亿日元
叼着奶瓶逛酒吧 : 所以说做程序员也要懂点法律知识
.net core 塑形资源
剑轩 : 收藏收藏
映射AutoMapper
剑轩 : 好是好,这个对效率影响大不大哇,效率高不高
ASP.NET Core 服务注册生命周期
剑轩 : http://www.tnblog.net/aojiancc2/article/details/167
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术