THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
catcherwong 7000290bd7 log: add log for config rpc server request handler 2 days ago
.github/workflows chore: update to nacos version to 2.0.1 2.0.2 3 days ago
_stylecop 🎉 Initial commit. 11 months ago
build config: update next version to 1.1.0 2 months ago
docs update docs 4 months ago
media 🎉 Initial commit. 11 months ago
parsers remove unofficial 4 months ago
samples docs: update sample and readme 2 days ago
src log: add log for config rpc server request handler 2 days ago
tests Merge branch 'Branch_b0227fa1' into ca 1 month ago
.editorconfig Add ConfigurationBuilder support (#105) 4 weeks ago
.gitignore check gitignore 5 months ago
Directory.Build.props Add ConfigurationBuilder support (#105) 4 weeks ago
LICENSE Initial commit 11 months ago
README.md docs: update sample and readme 2 days ago
README.zh-cn.md docs: update sample and readme 2 days ago
nacos-sdk-csharp.sln Add ConfigurationBuilder support (#105) 4 weeks ago

README.md

nacos-sdk-csharp             中文

csharp(dotnet core) implementation of nacos OpenAPI.

Build Release

Installation

Choose a package that you need.

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

NOTE: The packages' name has remove the suffix unofficial.

Features

  • Basic OpenApi Usages
  • Integrate ASP.NET Core Configuration System
  • Service Registration and Discovery With ASP.NET Core
  • Integrate With Aliyun ACM
  • ...

Basic Usage

Simple Configuration Usage

  1. Configure in Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .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.AddNacosConfiguration(c.GetSection("NacosConfig"), Nacos.IniParser.IniConfigurationStringParser.Instance);
            // builder.AddNacosConfiguration(c.GetSection("NacosConfig"), Nacos.YamlParser.YamlConfigurationStringParser.Instance);
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        })
  1. Modify appsettings.json
{
  "NacosConfig": {
    "Listeners": [
      {
        "Optional": false,
        "DataId": "common",
        "Group": "DEFAULT_GROUP"
      },
      {
        "Optional": false,
        "DataId": "demo",
        "Group": "DEFAULT_GROUP"
      }
    ],    
    "Namespace": "csharp-demo",
    "ServerAddresses": [ "http://localhost:8848/" ],
    "UserName": "test2",
    "Password": "123456",
    "AccessKey": "",
    "SecretKey": "",
    "EndPoint": "acm.aliyun.com",
    "ConfigFilterAssemblies": ["YouPrefix.AssemblyName"],
    "ConfigFilterExtInfo": "some ext infomation"
  }
}
  1. Use via .NET Core's Way
[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";
    }

}

Service Registration and Discovery

  1. Service Registration

Configure in Program.cs

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

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        // ...

        services.AddNacosAspNet(Configuration, "nacos");
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // ...
    }
}

Modify appsettings.json

"nacos": {
    "EndPoint": "sub-domain.aliyun.com:8080",
    "ServerAddresses": [ "http://localhost:8848" ],
    "DefaultTimeOut": 15000,
    "Namespace": "cs",
    "ListenInterval": 1000,
    "ServiceName": "App1",
    "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": "",
    "Password": "",
    "ConfigUseRpc": true,
    "NamingUseRpc": true,
    "NamingLoadCacheAtStart": "",       
    "LBStrategy": "WeightRandom", //WeightRandom WeightRoundRobin
    "Metadata": {
      "aa": "bb",
      "cc": "dd"
    }
  }
  1. Service Discovery
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    private readonly Nacos.V2.INacosNamingService _svc;

    public ValuesController(Nacos.V2.INacosNamingService svc)
    {
        _svc = svc;
    }

    [HttpGet("test")]
    public async Task<IActionResult> Test()
    {        
        // need to know the service name.
        var instance = await _svc.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();
        }
    }
}