Microservice Configuration Center Nacos .NET 5

Microservice Configuration Center Nacos .NET 5

A demo solution for the configuration center of microservices based on Nacos.

Last updated 5/17/2022 10:14 PM
蓝创精英团队
5 min read
Category
.NET
Tags
.NET C# Architecture Design Web API

Based on Nacos, here is a demo about a microservice configuration center solution.

Nacos is open-source, and Alibaba Cloud also offers a paid version of its service. Since the company relies on Alibaba Cloud's service system, using Nacos as the configuration center is highly feasible. So, here is an example based on it.

1. How to Set Up the Environment

Its environment is relatively complex and requires Docker services, a Demo service, and the corresponding MySQL database:

  1. Docker provides the Nacos service.
  2. WebDemo.
  3. The specified database required by MySQL.

2. Obtain the Official Table Structure

The official C# demo address is: https://github.com/nacos-group/nacos-sdk-csharp

The official address is here: https://github.com/alibaba/nacos.git

The SQL script is located at nacos\distribution\conf\nacos-mysql.sql

My project will provide the required sql.

Just insert the specified script, but you must have this database first.

Finally, you will see the following tables:

3. Start the Docker Service

I am using Docker Desktop by default. Just enter the command and it's done.

If you also use this Docker, you can refer to my previous articles about Docker.

docker run --name nacos  -d -p 8848:8848 ^
-e MODE=standalone ^
-e MYSQL_SERVICE_HOST=192.168.1.8 ^
-e MYSQL_SERVICE_DB_NAME=nacos_config ^
-e MYSQL_SERVICE_PORT=3306 ^
-e MYSQL_SERVICE_USER=root ^
-e MYSQL_SERVICE_PASSWORD=123456 ^
nacos/nacos-server

How to check if the service is OK?

You can visit http://localhost:8848/nacos/#/login in your browser.

Then, you can log in to the platform and see what's there.

The initial username and password are both nacos.

4. Add the Corresponding Configuration Information

  1. First, this is the configuration menu we need to add.
  2. Second, the corresponding namespace.
  3. Third, the specific configuration needed.

I added a new namespace called Test.

Then, I added two configurations in each as follows:

5. Create a New WebAPI Project

Create a default webapi project, then introduce the following nuget package:

nacos-sdk-csharp.AspNetCore

Also, you need to modify the default Program class to the following configuration:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        })
        .ConfigureAppConfiguration((context, builder) =>
        {
            var c = builder.Build();

            // read configuration from config files
            // it will use default json parser to parse the configuration store in nacos server.
            builder.AddNacosV2Configuration(c.GetSection("NacosConfig"));
            // you also can specify ini or yaml parser as well.
            // builder.AddNacosV2Configuration(c.GetSection("NacosConfig"), Nacos.IniParser.IniConfigurationStringParser.Instance);
            // builder.AddNacosV2Configuration(c.GetSection("NacosConfig"), Nacos.YamlParser.YamlConfigurationStringParser.Instance);
        });

Another thing to note is the most important configuration file (appsettings.json) as follows:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "NacosConfig": {
    "Listeners": [
      {
        "Optional": false,
        "DataId": "conn",
        "Group": "DEFAULT_GROUP"
      },
      {
        "Optional": false,
        "DataId": "other",
        "Group": "DEFAULT_GROUP"
      }
    ],
    "Tenant": "1806893a-7997-4657-9325-d4294fbf0f4a",
    "ServerAddresses": ["http://192.168.1.8:8848/"],
    "UserName": "nacos",
    "Password": "nacos",
    "ConfigUseRpc": false,
    "NamingUseRpc": false
  }
}

Among them, Tenant is the ID of the specified configuration center namespace, and Listeners are the Data IDs of the configurations under this namespace.

The ConfigUseRpc and NamingUseRpc parameters are required. If using HTTP protocol, both are false; if using gRPC protocol, both are true (an error will occur if not specified).

To enhance the demo effect, I modified the default controller method to read the specified configuration:

private readonly IConfiguration _configuration;
public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
{
    _logger = logger;
    _configuration = configuration;
}

public IActionResult Index(string key)
{
    if (string.IsNullOrWhiteSpace(key))
    {
        return Content("key is empty!");
    }
    return Content(_configuration[key]);
}

Effect after startup

Visit http://localhost:38889/home?key=mysql as follows:

Visit http://localhost:38889/home?key=other as follows:

Visit http://localhost:38889/home?key=redis as follows:

You can see all the corresponding configuration information has been retrieved.

At this point, I dynamically modify the configuration information on Nacos:

Then, check again to see if it is the latest:

It is already the latest, and the console has directly updated to the latest configuration:

This configuration center is also quite convenient to use.

6. Finally, here is the GitHub address

Keep Exploring

Related Reading

More Articles
Same category / Same tag 1/19/2024

FluentValidation Validation Tutorial Based on .NET

FluentValidation is a validation framework based on .NET development. It is open-source, free, and elegant, supporting chained operations, easy to understand, feature-complete, and can be deeply integrated with MVC5, WebApi2, and ASP.NET Core. The component provides over a dozen commonly used validators, good scalability, support for custom validators, and support for localization and multilingual.

Continue Reading