首页 > 其他 > 详细

consul

时间:2020-05-26 22:06:22      阅读:106      评论:0      收藏:0      [点我收藏+]
ubuntu安装
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端口服务被移除

技术分享图片

consul

原文:https://www.cnblogs.com/hwxing/p/12952995.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!