欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

.Net中使用Consul實(shí)現(xiàn)服務(wù)高可用的方法

 更新時(shí)間:2025年07月01日 10:47:49   作者:勿芮介  
Consul作為分布式服務(wù)發(fā)現(xiàn)工具,支持服務(wù)注冊(cè)、健康檢查等功能,能有效提升系統(tǒng)可用性,本文給大家介紹.Net中使用Consul實(shí)現(xiàn)服務(wù)高可用的相關(guān)知識(shí),感興趣的朋友一起看看吧

一、目的

在微服務(wù)架構(gòu)中,為了保證服務(wù)的高可用,通常需要在服務(wù)使用中,通過(guò)負(fù)載均衡配置,來(lái)分發(fā)流量和提高系統(tǒng)可用性擴(kuò)展系統(tǒng)服務(wù)的吞吐能力。并消除系統(tǒng)中的單點(diǎn)故障,提升應(yīng)用系統(tǒng)的可用性。一般來(lái)說(shuō)Nginx就可以實(shí)現(xiàn)負(fù)載均衡的功能。但是,因?yàn)镹ginx無(wú)法靈活的動(dòng)態(tài)添加服務(wù),因此一般在微服務(wù)架構(gòu)中,會(huì)通過(guò)一些中間件來(lái)實(shí)現(xiàn),服務(wù)發(fā)現(xiàn)的框架常用的有:consul、zookeeper等。

這里主要介紹的是在.Net環(huán)境下Consul實(shí)現(xiàn)服務(wù)發(fā)現(xiàn)等相關(guān)功能。

二、Consul概述

Consul是一個(gè)分布式、高度可用的數(shù)據(jù)中心感知服務(wù)發(fā)現(xiàn)平臺(tái),包括簡(jiǎn)單的服務(wù)注冊(cè)、運(yùn)行狀況檢查、故障檢測(cè)和密鑰值存儲(chǔ)。 它基于這樣一個(gè)前提:數(shù)據(jù)中心中的每個(gè)節(jié)點(diǎn)都運(yùn)行一個(gè) Consul 代理,并充當(dāng)服務(wù)器或客戶端。 每個(gè)代理通過(guò)可縮放的 gossip 協(xié)議進(jìn)行通信。

三、安裝和部署

3.1 下載Consul

Consul官網(wǎng)地址:Consul | HashiCorp Developer,Consul安裝非常簡(jiǎn)單,在官網(wǎng),點(diǎn)擊download

ps:這里我們可以看到Consul支持多種操作系統(tǒng)可選,這里我們?cè)趙indow上測(cè)試,這里選擇windows。

3.2 安裝和運(yùn)行

Consul安裝:下載后,解壓即可。解壓后只有一個(gè)consul.exe可執(zhí)行文件。

Consul運(yùn)行命令如下(進(jìn)入CMD命令行):

cd 對(duì)應(yīng)盤符文件夾\consul_1.17.1_windows_amd64
 //啟動(dòng)Consul
 consul agent -dev
 //設(shè)置ip地址訪問(wèn)-需要時(shí)配置
 consul agent -dev -client=0.0.0.0

3.3 訪問(wèn)Consul的UI頁(yè)面

啟動(dòng)后會(huì)顯示如下內(nèi)容:

瀏覽器中訪問(wèn)地址,http://localhost:8500/判斷Consul服務(wù)是否運(yùn)行成功。

ps:以上是Consul基本的單機(jī)部署,為保證高可用可以對(duì)Consul進(jìn)行集群部署。

四、.Net中使用Consul

4.1 安裝Nuget包

在業(yè)務(wù)服務(wù)中Nuget安裝: Consul,把業(yè)務(wù)服務(wù)注冊(cè)到Consul中

dotnet add packages Consul

4.2 .Net注冊(cè)服務(wù)

把當(dāng)前服務(wù)的相關(guān)地址信息,添加到Consul中:

using Consul;
using Microsoft.Extensions.Configuration;
using System;
namespace MicroService.Framework;
public static class ConsulHelper
{
    /// <summary>
    /// Consul注冊(cè)
    /// </summary>
    /// <param name="configuration"></param>
    public static void ConsulRegist(this IConfiguration configuration)
    {
        //準(zhǔn)備鏈接Consul的Client
        ConsulClient client = new ConsulClient(c =>
        {
            c.Address = new Uri("http://localhost:8500/");
            c.Datacenter = "test1";
        });//找到consul
        string ip = string.IsNullOrWhiteSpace(configuration["ip"]) ? "127.0.0.1" : configuration["ip"];
        int port = string.IsNullOrWhiteSpace(configuration["port"]) ? 9001 : int.Parse(configuration["port"]);//命令行參數(shù)必須傳入
        //int weight = string.IsNullOrWhiteSpace(configuration["weight"]) ? 1 : int.Parse(configuration["weight"]);
        client.Agent.ServiceRegister(new AgentServiceRegistration()
        {
            ID = "service" + Guid.NewGuid(),//唯一id
            Name = "test_server",//Group--分組
            Address = ip,
            Port = port,
            //Tags = new string[] { weight.ToString() },//標(biāo)簽
            Check = new AgentServiceCheck()
            {
                Interval = TimeSpan.FromSeconds(10),//間隔10s一次
                HTTP = $"http://{ip}:{port}/Api/Health/Index",//健康檢測(cè)接口
                Timeout = TimeSpan.FromSeconds(3),//檢測(cè)等待時(shí)間
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(60)//失敗后多久移除
            }
        });
        //命令行參數(shù)獲取
        Console.WriteLine($"注冊(cè)成功:{ip}:{port}");
    }
}

程序啟動(dòng)時(shí)注冊(cè)一次:

4.3 服務(wù)健康檢測(cè)

增加一個(gè)健康檢測(cè)接口,接口映射到管道中間件中處理,自定義返回結(jié)果:

public static class HealthExtention
{
    public static void Health(this WebApplication app)
    {
        app.MapWhen(context => context.Request.Path.Equals("/Api/Health/Index"),
         applicationBuilder => applicationBuilder.Run(async context =>
         {
             Console.WriteLine($"This is Health Check");
             context.Response.StatusCode = (int)HttpStatusCode.OK;
             await context.Response.WriteAsync("OK");
         }));
    }
}

4.4 服務(wù)使用

運(yùn)行業(yè)務(wù)服務(wù),使用端口來(lái)區(qū)分不同的業(yè)務(wù)邏輯

dotnet run --urls=http://localhost:9001 --port=9001

五、調(diào)用Consul示例

客戶端需要引用Consul的組件,正常微服務(wù)模式下,客戶端只需要請(qǐng)求網(wǎng)關(guān)即可,請(qǐng)求通過(guò)網(wǎng)關(guān)會(huì)轉(zhuǎn)發(fā)到其他服務(wù)層。

客戶端調(diào)用Consul中的服務(wù)示例

  //consul獲取服務(wù)api/users/all也得知道
  string url = null;
  url = "http://test_server/api/users/all";//consul就像dns--只是負(fù)責(zé)解析ip:port--清單
  ConsulClient client = new ConsulClient(c =>
  {
      c.Address = new Uri("http://localhost:8500/");
      c.Datacenter = "test1";
  });
  var response = client.Agent.Services().Result.Response;//獲取服務(wù)清單
  Uri uri = new Uri(url);
  string groupName = uri.Host;
  //服務(wù)實(shí)例
  AgentService agentService = null;
  var dictionary = response.Where(s => s.Value.Service.Equals(groupName, StringComparison.OrdinalIgnoreCase)).ToArray();
  {
      //agentService = dictionary[0].Value;//寫死第一個(gè)
  }
  {
      輪詢策略 也是平均,但是太僵硬了
      agentService = dictionary[iIndex++ % dictionary.Length].Value;
  }
    //可自定義負(fù)載策略
  url = $"{uri.Scheme}://{agentService.Address}:{agentService.Port}{uri.PathAndQuery}";
  string content = InvokeApi(url);
  var res = JsonConvert.DeserializeObject<IEnumerable<User>>(content);

六、文章總結(jié)

在微服務(wù)架構(gòu)中,使用Consul作為服務(wù)發(fā)現(xiàn)和配置管理的工具是非常常見的。Consul由HashiCorp開發(fā),提供了一個(gè)完整的解決方案,其中包括服務(wù)發(fā)現(xiàn)、健康檢查、鍵值存儲(chǔ)以及多數(shù)據(jù)中心支持。

把之所學(xué),以文載之~ 歡迎大家多多交流

相關(guān)引用:

https://zhuanlan.zhihu.com/p/701107409

使用 Consul 作為成員管理器 - .NET | Microsoft Learn

到此這篇關(guān)于.Net中使用Consul實(shí)現(xiàn)服務(wù)高可用的文章就介紹到這了,更多相關(guān).net Consul服務(wù)高可用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論