2.2微服务-consul

微服务2.0 consul

1、下载consul 并启动,浏览器打开localhost:8500

1
命令 启动 consul agent -dev

 

2、项目安装consul nuget包

 <PackageReference Include="Consul" Version="1.6.10.9" />

 

3、新建consul扩展类、并在站点启动完成前调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
using Consul;
 
namespace ApiService.Extensions
{
    public static class ConsulExtend
    {
        public static void Regist(this IConfiguration configuration)
        {
            string ip = configuration["ip"];
            int port = int.Parse(configuration["port"]);
 
            ConsulClient client = new ConsulClient(c =>
            {
                c.Address = new Uri("http://localhost:8500");
                c.Datacenter = "dc1";
            });
 
            client.Agent.ServiceRegister(new AgentServiceRegistration()
            {
                ID = $"service{Guid.NewGuid()}",
                Name = "users",
                Address = ip,
                Port = port,
                //Tags =new string[] { "50"},//标签,可用分配权重
                Check = new AgentServiceCheck()
                {
                    Interval = TimeSpan.FromSeconds(10),//10秒检测一次
                    HTTP = $"http://{ip}:{port}/health/check",//心跳地址
                    Timeout = TimeSpan.FromSeconds(5),//检查等待时间
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20)//失败多久移除
                }
            });
        }
    }
}

 

1
2
3
4
5
6
app.MapControllers();
 
//注册Consul
ConsulExtend.Regist(builder.Configuration);
 
app.Run();

 

4、完成服务注册

 

5、在客户端项目,服务发现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var response = new ConsulClient(c =>
    {
        c.Address = new Uri("http://localhost:8500");
        c.Datacenter = "dc1";
    }).Agent.Services().Result.Response;
 
    var agentServices = response.Where(s => s.Value.Service.Equals("users", StringComparison.OrdinalIgnoreCase)).ToArray();
 
    var agentService = agentServices.OrderBy(s => Guid.NewGuid()).FirstOrDefault().Value;
 
    //服务策略【平均、随机、轮询、权重】
 
    //随机策略
    string url = $"http://{agentService.Address}:{agentService.Port}/user/getlist";
 
    var httpResponse = await new HttpClient().GetAsync(url).Result.Content.ReadAsStringAsync(); ;
 
    Console.WriteLine($"Url:{url} Rsponse:{httpResponse}");
 
    Console.ReadKey();

 

6、docker 安装consul

文档链接

1
2
3
4
5
6
7
8
9
拉取镜像 docker pull consul
 
运行单机
docker run \
    -d \
    -p 8500:8500 \
    -p 8600:8600/udp \
    --name=badger \
    consul agent -server -ui -node=server-1 -bootstrap-expect=1 -client=0.0.0.0 
posted @   有只烤鸡  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示