趁着刚过完年,还没有开始做业务的时候,学习下consul 概念自己去官网看,这里只讲下具体实现

官网下载https://www.consul.io/downloads 我下载的是Windows版本

启动consul命令 

consul agent -dev -client 0.0.0.0

新建.net5的api项目,.net5直接默认是swagger

4.新建扩展服务注册到Consul方法,ConsulExtenions.cs

 

  1. public static void ConsulRegist(this IConfiguration configuration)
  2. {
  3. try
  4. {
  5. string ip = configuration["ip"];
  6. string port = configuration["port"];
  7. string weight = configuration["weight"];
  8. string consulAddress = configuration["ConsulAddress"];
  9. string consulCenter = configuration["ConsulCenter"];
  10. ConsulClient client = new ConsulClient(c =>
  11. {
  12. c.Address = new Uri(consulAddress);
  13. c.Datacenter = consulCenter;
  14. });
  15. client.Agent.ServiceRegister(new AgentServiceRegistration()
  16. {
  17. ID = "CommService" + Guid.NewGuid(),//--唯一的
  18. Name = "CommService",//分组---根据Service
  19. Address = ip,
  20. Port = int.Parse(port),
  21. Tags = new string[] { weight.ToString() },//额外标签信息
  22. Check = new AgentServiceCheck()
  23. {
  24. Interval = TimeSpan.FromSeconds(12),
  25. HTTP = $"http://{ip}:{port}/Api/Health/Index", // 给到200
  26. Timeout = TimeSpan.FromSeconds(5),
  27. DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20)
  28. }//配置心跳
  29. });
  30. Console.WriteLine($"{ip}:{port}--weight:{weight}"); //命令行参数获取
  31. }
  32. catch (Exception ex)
  33. {
  34. Console.WriteLine($"Consul注册:{ex.Message}");
  35. }
  36. }

ip port 配置在appsettings.json里面

  1. {
  2. "Logging": {
  3. "LogLevel": {
  4. "Default": "Information",
  5. "Microsoft": "Warning",
  6. "Microsoft.Hosting.Lifetime": "Information"
  7. }
  8. },
  9. "AllowedHosts": "*",
  10. "ip": "localhost",
  11. "port": 5000,
  12. "weight": 1,
  13. "ConsulAddress": "http://127.0.0.1:8500",
  14. "ConsulCenter": "dc1"
  15. }

Startup注册ConsulRegist方法

  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  2. {
  3. //if (env.IsDevelopment())
  4. //{
  5. app.UseDeveloperExceptionPage();
  6. app.UseSwagger();
  7. app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "comm.api v1"));
  8. //}
  9. // app.UseHttpsRedirection();
  10. app.UseRouting();
  11. app.UseAuthorization();
  12. app.UseEndpoints(endpoints =>
  13. {
  14. endpoints.MapControllers();
  15. });
  16. // Consul注册
  17. this.Configuration.ConsulRegist();
  18. }

可以用dotnet 启动2个comm.api.dll  端口号自己随便取,我取的5000和6000 HealthController为配置的心跳api返回的结果

再来看下Consul 会发现多了CommService

2 Instances为端口号5000和6000的api

注册完成了,接下来实现调用看效果图

调用代码

  1. public static AgentService ChooseService(string serviceName)
  2. {
  3. using (ConsulClient client = new ConsulClient(c => c.Address = new Uri("http://localhost:8500")))
  4. {
  5. var services = client.Agent.Services().Result.Response;
  6. // 找出目标服务
  7. var targetServices = services.Where(c => c.Value.Service.Equals(serviceName)).Select(s => s.Value);
  8. // 实现随机负载均衡
  9. var targetService = targetServices.ElementAt(new Random().Next(1, 1000) % targetServices.Count());
  10. Console.WriteLine($"{DateTime.Now} 当前调用服务为:{targetService.Address}:{targetService.Port}");
  11. return targetService;
  12. }
  13. }
  1. public string GetCommUrl()
  2. {
  3. AgentService agentService = ConsulClientExtenions.ChooseService("CommService");
  4. string url = $"http://{agentService.Address}:{agentService.Port}/api/Comm/GetProvince";
  5. return url;
  6. }

需要demo的留言

版权声明:本文为panjuan原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/panjuan/p/14434827.html