background

ASP.NET Core with Nacos for configuration management and service discovery explains how to make asp. NET Core program access Nacos, the previous SDK is more Nacos Open API encapsulation and service registration and discovery encapsulation.

Configuration of this piece at that time did not have too much processing, use sometimes feel not particularly handy, so it and. The configuration of NET Core is combined to make it easier to use.

What’s the easy way to do that?

It’s pretty much the same as the original, except for a little bit more providers, you can take an IConfiguration and take an IOptions configuration.

Easier to migrate seamlessly!

Of course, this SDK comes from Old Huang’s hand, there will inevitably be some pits and bugs, please bear with me!!

The premise condition

  1. Start the Nacos Server

The easiest way is to start a standalone version with Docker.

docker-compose -f example/standalone-mysql-8.yaml up
Copy the code
  1. Create a.net Core project and install the corresponding Nuget package

I’ll use ASP.NET Core Web Api as an example and install the nuget package below

Dotnet add package nacos - SDK - csharp - unofficial. Extensions. The Configuration - version 0.2.6Copy the code

More directly, modify csPROj directly

The < ItemGroup > < PackageReference Include = "nacos - SDK - csharp - unofficial. Extensions. The Configuration" Version = "0.2.6" / > </ItemGroup>Copy the code

configure

Open program. cs and add the provider configuration to CreateHostBuilder.

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, the base configuration of Nacos can be read from the configuration file
                 //builder.AddNacosConfiguration(c.GetSection("nacosconfig"));
                 
             })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
Copy the code

Also, we need to modify appsettings.json to include the configuration of Nacos, mainly 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"]}}Copy the code

Well, that’s the end of configuring Nacos. Next, all you need to do is maintain the configuration on the NACOS console.

Configured to use

Creating 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; }}Copy the code

To verify the IOptions mode, add some code to Startup

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

Here’s how it’s actually used!

[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
       
         options, IOptionsSnapshot
        
          sOptions, IOptionsMonitor
         
           _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"; }}Copy the code

From the above code, it should look as familiar as it could be! The use of these configurations is. NET Core provides the most original, original taste.

Launch access to this interface and you can see the following output.

Modify this configuration on the console.

On a second visit, you can see that the new configuration has been read except for IOptions.

The reason IOptions doesn’t get the latest configuration is because its default implementation doesn’t update, meaning it doesn’t change from start to finish.

In the case of configuration changes, do not use IOptions, use IOptionsSnapshot and IOptionsMonitor instead!

conclusion

Here’s how to make. NET Core is more easily connected to the Nacos configuration method, hope to help you.

If you are interested in nacOS-SDK-CHARp, you are welcome to develop and maintain this project together.

This article was first published on my official account: Not just Old Huang

Those who are interested can take a look.