MyGit

nacos-group/nacos-sdk-csharp

Fork: 92 Star: 422 (更新于 2024-12-14 19:05:35)

license: Apache-2.0

Language: C# .

This nacos csharp sdk

最后发布版本: v1.3.8 ( 2024-08-20 11:19:53)

官方网址 GitHub网址

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 MSE/ACM
  • ...

Find more information on the documents pages:

https://nacos-sdk-csharp.readthedocs.io/en/latest/

Basic Usage

Simple Configuration Usage

  1. Configure in Program.cs
// after v1.3.3, we can use UseNacosConfig to simplify
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .UseNacosConfig(section: "NacosConfig", parser: null, logAction: null)
        // .UseNacosConfig(section: "NacosConfig", parser: Nacos.YamlParser.YamlConfigurationStringParser.Instance logAction: null)
        // .UseNacosConfig(section: "NacosConfig", parser: Nacos.IniParser.IniConfigurationStringParser.Instance logAction: null)       
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

// before v1.3.3
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.AddNacosV2Configuration(c.GetSection("NacosConfig"), Nacos.IniParser.IniConfigurationStringParser.Instance);
            // builder.AddNacosV2Configuration(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",  // Please set the value of Namespace ID !!!!!!!!
    "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", // Please set the value of Namespace ID !!!!!!!!
    "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();
        }
    }
}

最近版本更新:(数据更新于 2024-09-03 01:00:44)

2024-08-20 11:19:53 v1.3.8

2024-07-11 10:11:50 v1.3.7

2024-06-27 09:00:46 v1.3.6

2023-04-11 23:09:47 v1.3.5

2022-08-10 22:25:14 v1.3.4

2022-05-30 23:11:39 v1.3.3

2022-03-15 00:25:15 v1.3.2

2022-01-20 08:20:56 v1.3.1

2021-12-09 19:09:14 v1.3.0

2021-11-07 15:38:23 v1.2.2

主题(topics):

csharp, dotnet

nacos-group/nacos-sdk-csharp同语言 C#最近更新仓库

2024-12-20 06:41:40 microsoft/PowerToys

2024-12-07 22:15:43 Pik-4/HsMod

2024-12-01 20:18:03 BililiveRecorder/BililiveRecorder

2024-11-26 14:48:43 Azure/azure-sdk-for-net

2024-11-19 11:38:46 jellyfin/jellyfin

2024-11-15 10:33:01 DigitalRuby/IPBan