1.安装Consul包
2.下载安装并且运行Consul
https://www.consul.io/downloads.html
3.在Program.cs中修改Main方法,允许命令行
public static void Main(string[] args)
{
var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddCommandLine(args).Build();
CreateHostBuilder(args).Build().Run();
}
4.编写心跳检测Controller,用于检测服务是否还保持连接
[Route("api/[controller]")]
[ApiController]
public class HealthController : Controller
{
private readonly ILogger<HealthController> _logger;
public HealthController(ILogger<HealthController> logger)
{
_logger = logger;
}
// GET
[HttpGet]
public IActionResult Get()
{
_logger.LogInformation("Health Check");
return Ok();
}
}
5.编写扩展方法注册Consul
public static class ConsulRegister
{
public static void RegistConsul(this IConfiguration configuration)
{
#region 注册consul
string ip = configuration["ip"] ?? "Localhost";
//部署到不同服务器地址的时候不能写成127.0.0.1或者0.0.0.0,因为这是让服务消费者调用的地址
int port = string.IsNullOrWhiteSpace(configuration["port"]) ? 44344 : int.Parse(configuration["port"]);
var client = new ConsulClient(obj =>
{
obj.Address = new Uri("http://127.0.0.1:8500");
obj.Datacenter = "dc1";
});//向consul注册服务
var result = client.Agent.ServiceRegister(new AgentServiceRegistration()
{
ID="apiserviceTest_"+Guid.NewGuid(),
Name= "apiserviceTest",
Address=ip,
Port=port,
Tags=new string[] {},
Check=new AgentServiceCheck()
{
DeregisterCriticalServiceAfter=TimeSpan.FromSeconds(5),
Interval=TimeSpan.FromSeconds(10),
HTTP=$"http://{ip}:{port}/api/health",
Timeout=TimeSpan.FromSeconds(5)
}
});
#endregion
}
}
6.生成并且通过命令行运行项目
运行命令dotnet 项目名.dll --urls="http://*:5726" --ip="127.0.0.1" --port=5726 --weight=2
7.再次访问 http://localhost:8500
8.consul服务搭建完成