一、新建项目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}");
}
}
}
}
五、运行效果