天天看點

ASP.NET Core 學習記錄 - 微服務接入 Nacos配置中心

1、安裝Nuget包

dotnet add package nacos-sdk-csharp
dotnet add package nacos-sdk-csharp.AspNetCore
dotnet add package nacos-sdk-csharp.Extensions.Configuration
dotnet add package nacos-sdk-csharp.YamlParser
dotnet add package nacos-sdk-csharp.IniParser           
注: 從1.0.0版本之後,包名裡面的 `unofficial` 字尾已經被移除,帶 `unofficial` 的包已經不再維護更新,請盡早更新到最新版本。

2、服務注冊和發現

2.1 在Startup.cs檔案中增加如下配置:

public Startup(IConfiguration configuration)
{
     Configuration = configuration;
}

private readonly IConfiguration Configuration { get; }           

在ConfigureServices函數中增加如下代碼段:

services.AddNacosAspNet(Configuration, "nacos");           

2.2 修改appsettings.json檔案,增加如下内容:

"nacos": {
    "EndPoint": "",
    "ServerAddresses": [ "http://IP位址:8848/" ], // nacos服務端位址
    "DefaultTimeOut": 15000,
    "Namespace": "8aa86aef-545d-43d1-bb1e-44c788767928", // 服務注冊到的命名空間id
    "ListenInterval": 1000,
    "ServiceName": "service-name", //服務名稱
    "GroupName": "DEFAULT_GROUP", //服務分組
    "ClusterName": "DEFAULT",
    "Ip": "",
    "PreferredNetworks": "", // select an IP that matches the prefix as the service registration IP
    "Port": 0,
    "Weight": 100, // 權重
    "RegisterEnabled": true,
    "InstanceEnabled": true,
    "Ephemeral": true,
    "Secure": false,
    "AccessKey": "",
    "SecretKey": "",
    "UserName": "nacos",
    "Password": "nacos",
    "ConfigUseRpc": true, // 為true時,通過 gRPC 去和 nacos server 互動,nacos 2.x版本要設定為true": null,
    "NamingUseRpc": true, // 為true時,通過 gRPC 去和 nacos server 互動, nacos 2.x版本要設定為true": null,
    "NamingLoadCacheAtStart": "",
    "LBStrategy": "WeightRandom", //  WeightRandom WeightRoundRobin
    "Metadata": {}
  },           
其中指令空間、服務分組都可以自行而配置。

2.3 服務發現

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    private readonly Nacos.V2.INacosNamingService _nacosNamingService;

    public ValuesController(Nacos.V2.INacosNamingService nacosNamingService)
    {
        _nacosNamingService = nacosNamingService;
    }

    [HttpGet("test")]
    public async Task<IActionResult> Test()
    {
        // 被調用方的服務名稱
        var instance = await _nacosNamingService.SelectOneHealthyInstance("App2", "DEFAULT_GROUP")
        var host = #34;{instance.Ip}:{instance.Port}";

        var baseUrl = instance.Metadata.TryGetValue("secure", out _)
            ? #34;https://{host}"
            : #34;http://{host}";

        if(string.IsNullOrWhiteSpace(baseUrl))
        {
            return "empty";
        }

        var url = #34;{baseUrl}/api/values";

        using (HttpClient client = new HttpClient())
        {
            var result = await client.GetAsync(url);
            return await result.Content.ReadAsStringAsync();
        }
    }
}           

3、擷取配置,切換為從Nacos配置清單擷取相應DataId的配置

3.1 在Program.cs檔案中CreateHostBuilder函數裡增加如下配置

.ConfigureAppConfiguration((context, builder) =>
{
    var c = builder.Build();
    builder.AddNacosV2Configuration(c.GetSection("NacosConfig"),
        logAction: x => x.AddSerilog(logger));
})           

3.2 修改appsettings.json檔案,增加如下内容:

"NacosConfig": {
    "Listeners": [
      {
        "Optional": false,
        "DataId": "service-name",
        "Group": "DEFAULT_GROUP"
      }
    ],
    "Namespace": "8aa86aef-545d-43d1-bb1e-44c788767928",
    "ServerAddresses": [ "http://IP位址:8848/" ],
    "UserName": "nacos",
    "Password": "nacos",
    "AccessKey": "",
    "SecretKey": "",
    "EndPoint": "",
    "ConfigFilterAssemblies": [ "AuthServer.Host" ], //程式集名稱,比如鑒權服務
    "ConfigFilterExtInfo": "some ext infomation"
  }           

3.3 用原生的.NET Core方式來讀取Nacos配置

[ApiController]
[Route("api/[controller]")]
public class ConfigController : ControllerBase
{
    private readonly IConfiguration _configuration;
    private readonly AppSettings _settings;
    private readonly AppSettings _sSettings;
    private readonly AppSettings _mSettings;

    public ConfigController(
        IConfiguration configuration,
        IOptions<AppSettings> options,
        IOptionsSnapshot<AppSettings> sOptions,
        IOptionsMonitor<AppSettings> _mOptions
        )
    {
        _logger = logger;
        _configuration = configuration;
        _settings = options.Value;
        _sSettings = sOptions.Value;
        _mSettings = _mOptions.CurrentValue;
    }

    [HttpGet]
    public string Get()
    {
        // ....

        return "ok";
    }

}           
注:在AuthServerHostModule類已注入;

4、調整原始appsettings.json檔案

将系統原先的配置,比如:資料庫連接配接、Redis連接配接等配置在項目中删除,拷貝到Nacos配置中心去;

5、Nacos配置清單增加相應的配置

配置内容來源于底4部分
ASP.NET Core 學習記錄 - 微服務接入 Nacos配置中心
{
  "ConnectionStrings": {
    "Default": "資料庫連接配接配置"
  },
  "CorsOrigins": "http://localhost:9527,http://localhost:44307,http://IP位址:9527,http://IP位址:44307",
  "ElasticSearch": {
    "Url": "http://IP位址:9200"
  },
  "Redis": {
    "IsEnabled": "true",
    "Configuration": "Redis資料庫配置位址"
  },
  "RabbitMQ": {
    "Connections": {
      "Default": {
        "HostName": "IP位址"
      }
    },
    "EventBus": {
      "ClientName": "MsDemo_AuthServer",
      "ExchangeName": "MsDemo"
    }
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}           

(此處已添加書籍卡片,請到今日頭條用戶端檢視)

(此處已添加紀錄片卡片,請到今日頭條用戶端檢視)