wget https://releases.hashicorp.com/consul/1.7.3/consul_1.7.3_linux_amd64.zip
unzip consul_1.7.3_linux_amd64.zip (需安装sudo apt-get install unzip)
sudo mv consul /usr/local/bin/
输入consul agent -dev
运行正常,但无法访问
再输入consul agent -dev -client 0.0.0.0
运行,可以通过外网访问
新建一个webapi项目
创建Util/consulHelper.cs
using System;
using Consul;
using Microsoft.Extensions.Configuration;
namespace WebApi.Util
{
public static class ConsulHelper
{
public static void UseConsulHelper(this IConfiguration configuration)
{
ConsulClient client = new ConsulClient(c =>{
c.Address = new Uri("http://39.108.54.23:8500");
c.Datacenter = "dc1";
});
// var response = client.Agent.Services().Result.Response; // 获取全部services
string ip = configuration["ip"];
int port = int.Parse(configuration["port"]);
// int weight = string.IsNullOrEmpty(configuration["weight"] ? 1 : int.Parse(configuration["weight"]));
client.Agent.ServiceRegister(new AgentServiceRegistration(){
ID = "service" + Guid.NewGuid(),
Name = "xing",
Address = ip,
Port = port,
Tags = new string[] {}
});
}
}
}
然后在 Startup.cs 中Configure类中最后添加
Configuration.UseConsulHelper();
编译之后放上linux上运行,然后打开consul页面,发现多了一个service
新增一个方法,发现服务
private static int index = 0;
public string find()
{
string url = "http://xing/api/value";
ConsulClient client = new ConsulClient(c => {
c.Address = new Uri("http://39.108.54.23:8500");
c.Datacenter = "dc1";
});
var response = client.Agent.Services().Result.Response;
Uri uri = new Uri(url);
string host = uri.Host;
var serviceDictionary = response.Where(r => r.Value.Service.Equals(host,StringComparison.OrdinalIgnoreCase)).ToArray();
if(serviceDictionary != null)
{
AgentService agentService;
// 轮询
agentService = serviceDictionary[index++%(serviceDictionary.Length)].Value;
url = $"{uri.Scheme}://{agentService.Address}:{agentService.Port}{uri.PathAndQuery}";
}
return url;
}
访问http://localhost:5000/api/value/find
在ConsulHelper.cs文件中代码修改如下
client.Agent.ServiceRegister(new AgentServiceRegistration(){
ID = "service" + Guid.NewGuid(),
Name = "xing",
Address = ip,
Port = port,
Tags = new string[] {},
Check = new AgentServiceCheck(){
Interval = TimeSpan.FromSeconds(10), // 间隔多久一次检查
HTTP = $"http://{ip}:{port}/api/health", // 检查api
Timeout = TimeSpan.FromSeconds(5), // 检查等待时间
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(30) // 失败后多久移除
}
});
添加HealthController.cs文件
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
namespace WebApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class HealthController:ControllerBase
{
private readonly IConfiguration _configuration;
public HealthController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpGet]
public IActionResult index()
{
Console.WriteLine(this._configuration["ip"]+":" + _configuration["port"]+" is health!");
return Ok();
}
}
}
接下来,需把之前的进程杀掉,重新编译,上传代码
运行以下命令,打开consul页面发现3个服务,每个都健康
dotnet WebApi.dll --urls="http://*:8081" --ip="127.0.0.1" --port=8081 &
dotnet WebApi.dll --urls="http://*:8082" --ip="127.0.0.1" --port=8082 &
dotnet WebApi.dll --urls="http://*:8083" --ip="127.0.0.1" --port=8083 &
把其中的8083端口进程杀掉,通过请求http://39.108.54.23:8080/api/value/get
也不会请求到8083端口的
等待一会后,8083端口服务被移除
原文:https://www.cnblogs.com/hwxing/p/12952995.html