一、建立項目ConsulWebRegCore
Nuget
<PackageReference Include="Consul" Version="1.6.1.1" />
二、配置檔案appsettings.json
{
"ip": "192.168.1.108",
"port": "28903"
}
三、服務注冊
Startup.cs
using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ConsulWebRegCore
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddHealthChecks();
services.AddControllers();
}
public void ConsulConfig(ConsulClientConfiguration c)
{
c.Address = new Uri("http://192.168.1.117:8500");
c.Datacenter = "dc1";
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime applicationLifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapHealthChecks("/health");
});
string ip = Configuration["ip"];
int port = int.Parse(Configuration["port"]);
string serviceName = "ConsulWebRegCore";
string serviceId = serviceName + Guid.NewGuid();
using (var client = new ConsulClient(ConsulConfig))
{
//注冊服務到Consul
client.Agent.ServiceRegister(new AgentServiceRegistration()
{
ID = serviceId, //服務編号,不能重複
Name = serviceName, //服務名字
Address = ip,
Port = port,
Check = new AgentServiceCheck
{
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5), //服務停止多久後反注冊
Interval = TimeSpan.FromSeconds(10),
HTTP = $"http://{ip}:{port}/health",
Timeout = TimeSpan.FromSeconds(5)
}
}).Wait();
}
applicationLifetime.ApplicationStopped.Register(() =>
{
using (var client = new ConsulClient(ConsulConfig))
{
//登出服務
//client.Agent.ServiceDeregister(serviceId).Wait();
}
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
四、服務發現
WeatherForecastController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ConsulWebRegCore.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IActionResult Get()
{
using (var consul = new Consul.ConsulClient(c =>
{
c.Address = new Uri("http://192.168.1.117:8500");
}))
{
//取出全部的MsgService服務
var services = consul.Agent.Services().Result.Response.Values.Where(p => p.Service.Equals("ConsulWebRegCore", StringComparison.OrdinalIgnoreCase));
//用戶端負載均衡,随機選出一台服務
Random rand = new Random();
var index = rand.Next(services.Count());
var s = services.ElementAt(index);
return Ok($"Index={index},ID={s.ID},Service={s.Service},Addr={s.Address},Port={s.Port}");
}
}
}
}
五、運作效果