Read the configuration of Nacos in the most native way in. NET Core

Keywords: SDK JSON Docker MySQL

background

Before that, Lao Huang wrote an article "ASP.NET Core combines with Nacos to complete configuration management and service discovery", which briefly introduced how to connect. NET Core programs to Nacos. In the previous SDK, more open APIs of Nacos were encapsulated and service registration and discovery were encapsulated.

At that time, there was not too much processing in configuration, and sometimes it would not be easy to use, so it was combined with the configuration of. NET Core to make it easier to use.

How easy is it?

It can be said as like as two peas of provider, the other operations are the same as the original ones. You want to use IConfiguration for IConfiguration, and you want to use IOptions series to use IOptions series.

It's easier to move seamlessly!

Of course, this SDK is made by Lao Huang, and there will inevitably be some holes and bug s. Please forgive me!!

prerequisite

  1. Start Nacos Server

The simplest way is to start a stand-alone version with docker.

docker-compose -f example/standalone-mysql-8.yaml up
  1. Create a. NET Core project and install the nuget package

Here we will use ASP.NET Core Web Api as an example and install the following nuget package

dotnet add package nacos-sdk-csharp-unofficial.Extensions.Configuration --version 0.2.6

Directly modify csproj

<ItemGroup>
    <PackageReference Include="nacos-sdk-csharp-unofficial.Extensions.Configuration" Version="0.2.6" />
</ItemGroup>

Configure

Open Program.cs and add the provider configuration of Nacos in CreateHostBuilder, which are all basic configurations of Nacos.

public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
             .ConfigureAppConfiguration((context, builder) =>
             {
                 var c = builder.Build();
                 var dataId = c.GetValue<string>("nacosconfig:DataId");
                 var group = c.GetValue<string>("nacosconfig:Group");
                 var tenant = c.GetValue<string>("nacosconfig:Tenant");
                 var optional = c.GetValue<bool>("nacosconfig:Optional");
                 var serverAddresses = c.GetSection("nacosconfig:ServerAddresses").Get<List<string>>();
                               
                 // Before version 0.2.6, only this method was supported
                 builder.AddNacosConfiguration(x =>
                 {
                     x.DataId = dataId;
                     x.Group = group;
                     x.Tenant = tenant;
                     x.Optional = optional;
                     x.ServerAddresses = serverAddresses;
                 });

                 ////After version 0.2.6, you can read the basic configuration of Nacos from the configuration file
                 //builder.AddNacosConfiguration(c.GetSection("nacosconfig"));
                 
             })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });

Similarly, we need to modify appsettings.json to include the configuration of Nacos, which is mainly used to distinguish the configuration sources of different environments.

{
  "Logging": {
    "LogLevel": {
        "Default": "Warning",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime" :"Information"
    }  
  },
  "nacosconfig":{
    "Optional": false,
    "DataId": "msconfigapp",
    "Group": "",
    "Tenant": "ca31c37e-478c-46ed-b7ea-d0ebaa080221",
    "ServerAddresses": ["localhost:8848"]
  }
}

OK, so that's the end of the Nacos configuration. The next step is to maintain the configuration in the Nacos console.

Configure use

Create a new configuration

Add a corresponding entity class

public class AppSettings
{
	public string Str { get; set; }

	public int Num { get; set; }

	public List<int> Arr { get; set; }

	public SubObj SubObj { get; set; }
}

public class SubObj
{
	public string a { get; set; }
}

To verify the IOptions mode, add some code to Startup

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
    services.AddControllers();
}

Here is the real use!

[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
        )
    {
        _configuration = configuration;
        _settings = options.Value;
        _sSettings = sOptions.Value;
        _mSettings = _mOptions.CurrentValue;
    }
    
    [HttpGet]
    public string Get()
    {
        string id = Guid.NewGuid().ToString("N");
    
        Console.WriteLine($"============== begin {id} =====================");
    
        var conn = _configuration.GetConnectionString("Default");
        Console.WriteLine($"{id} conn = {conn}");
    
        var version = _configuration["version"];
        Console.WriteLine($"{id} version = {version}");
    
        var str1 = Newtonsoft.Json.JsonConvert.SerializeObject(_settings);
        Console.WriteLine($"{id} IOptions = {str1}");
    
        var str2 = Newtonsoft.Json.JsonConvert.SerializeObject(_sSettings);
        Console.WriteLine($"{id} IOptionsSnapshot = {str2}");
    
        var str3 = Newtonsoft.Json.JsonConvert.SerializeObject(_mSettings);
        Console.WriteLine($"{id} IOptionsMonitor = {str3}");
    
        Console.WriteLine($"===============================================");
    
        return "ok";
    }
}

From the above code, it seems that you should be familiar with it! The usage of these configurations is the most original and original provided in. NET Core.

To start accessing this interface, you can see the following output.

Modify the configuration in the console.

When you visit again, you can see that the new configuration has been read in addition to IOptions.

The reason IOptions does not get the latest configuration is that its default implementation will not update, that is, it will not change from start to end.

In the case of configuration changes, please do not use IOptions as much as possible. Instead, use IOptions snapshot and IOptionsMonitor!

summary

This article introduces how to make it easier for. NET Core to connect with Nacos configuration. I hope it can help you.

If you are interested in the Nacos SDK Charp project, you are welcome to develop and maintain the project together.

This article starts with my official account: old age is not the only thing.

You can pay attention to what you are interested in.

Posted by beanfair on Sun, 26 Apr 2020 16:54:44 -0700