ASP.NET Core 微服务接入 Nacos配置中心

943 阅读2分钟

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 = $"{instance.Ip}:{instance.Port}";

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

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

        var url = $"{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部分

image.png

{
  "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": "*"
}