代码拉取完成,页面将自动刷新
基于C#(dotnet core)实现 nacos OpenAPI 的非官方版本
Platform | Build Server | Master Status |
---|---|---|
Github Action | Linux/OSX |
|
dotnet add package nacos-sdk-csharp-unofficial
Program.cs
进行如下配置public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, builder) =>
{
var c = builder.Build();
// read configuration from config files
builder.AddNacosConfiguration(c.GetSection("NacosConfig"));
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
appsettings.json
{
"NacosConfig": {
"Optional": false,
"DataId": "msconfigapp",
"Group": "",
"Tenant": "f47e0ae1-982a-4a64-aea3-52506492a3d4",
"ServerAddresses": [ "http://localhost:8848/" ],
"UserName": "test2",
"Password": "123456",
"AccessKey": "",
"SecretKey": "",
"EndPoint": "acm.aliyun.com"
}
}
[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";
}
}
在 Program.cs
中配置
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddNacosAspNetCore(Configuration);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
}
}
修改 appsettings.json
"nacos": {
"ServerAddresses": [ "http://localhost:8848" ],
"DefaultTimeOut": 15000,
"Namespace": "",
"ListenInterval": 1000,
"ServiceName": "App1"
}
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly INacosServerManager _serverManager;
public ValuesController(INacosServerManager serverManager)
{
_serverManager = serverManager;
}
[HttpGet("test")]
public async Task<IActionResult> Test()
{
// 这里需要知道被调用方的服务名
// 目前获取服务地址是随机的方式,后续会加入更多负载算法.
var baseUrl = await _serverManager.GetServerAsync("App2");
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();
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。