Net6集成Nacos实现服务注册
- 一、服务注册
- 1.创建WebAPI项目
- 2.安装Nuget包
- 3.注册Nacos
- Nacos配置文件(放在Appsetting.json或其他文件中)
- 4.创建Api控制器
- 5.运行效果
- 二、配置中心
- 1.设置配置
- 2.读取配置
- 3.展示效果
- 4.设置多个配置项
Nacos安装
nacos-sdk-csharp Nuget包作者博客
一、服务注册
1.创建WebAPI项目
2.安装Nuget包
nacos-sdk-csharp
nacos-sdk-csharp.AspNetCore
nacos-sdk-csharp.Extensions.Configuration
nacos-sdk-csharp.IniParser
nacos-sdk-csharp.YamlParser
Swashbuckle.AspNetCore
3.注册Nacos
builder.Services.AddNacosAspNet(builder.Configuration);
Nacos配置文件(放在Appsetting.json或其他文件中)
"nacos": {
"EndPoint": "",
"ServerAddresses": [ "http://127.0.0.1:8848" ],
"DefaultTimeOut": 15000,
"Namespace": "ec934a6e-36f5-4f1a-90f4-b74824da42a2",
"ListenInterval": 1000,
"ServiceName": "BaseApi",
"GroupName": "DEFAULT_GROUP",
"ClusterName": "DEFAULT",
"Ip": "",
"PreferredNetworks": "",
"Port": 0,
"Weight": 100,
"RegisterEnabled": true,
"InstanceEnabled": true,
"Ephemeral": true,
"Secure": false,
"AccessKey": "",
"SecretKey": "",
"UserName": "",
"Password": "",
"ConfigUseRpc": true,
"NamingUseRpc": false,
"NamingLoadCacheAtStart": "",
"LBStrategy": "WeightRandom",
"Metadata": {
"aa": "bb",
"cc": "dd"
}
}
4.创建Api控制器
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace NacosService.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly Nacos.V2.INacosNamingService _svc;
public ValuesController(Nacos.V2.INacosNamingService svc)
{
_svc = svc;
}
[HttpGet]
public string Get()
{
return "Ok~" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff");
}
/// <summary>
/// 从nacos中获取服务并选一个调用
/// </summary>
/// <returns></returns>
[HttpGet("test")]
public async Task<string> Test()
{
// 这里需要知道被调用方的服务名
var instance = await _svc.SelectOneHealthyInstance("BaseApi", "DEFAULT_GROUP");
var host = $"{"127.0.0.1"}:{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 var client = new HttpClient();
var result = await client.GetAsync(url);
return await result.Content.ReadAsStringAsync();
}
}
}
5.运行效果
二、配置中心
参考文章一
参考文章二
1.设置配置
设置如下配置信息
2.读取配置
注册配置中心
//添加配置中心
builder.Host.ConfigureAppConfiguration((context, builder) =>
{
var config = builder.Build();
builder.AddNacosV2Configuration(config.GetSection("NacosConfig"));
});
appsetting.json文件下增加如下配置信息
"NacosConfig": {
"Listeners": [
{
"Optional": false,
"DataId": "Test01",
"Group": "20231019"
}
],
"Optional": false,
"Namespace": "ec934a6e-36f5-4f1a-90f4-b74824da42a2",
"ServerAddresses": [ "http://127.0.0.1:8848/" ]
}
通过Configuration读取Nacos的配置信息
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace NacosService.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly Nacos.V2.INacosNamingService _svc;
private readonly IConfiguration _configuration;
public ValuesController(
Nacos.V2.INacosNamingService svc,
IConfiguration configuration)
{
_svc = svc;
_configuration = configuration;
}
[HttpGet]
public string Get()
{
return "Ok~" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff");
}
[HttpGet]
[Route("GetConfig")]
public string GetConfig()
{
var appName = _configuration["Name"];
return appName;
}
}
}
3.展示效果
4.设置多个配置项
添加三个配置选项
添加如下三个监听
"NacosConfig": {
"Listeners": [
{
"Optional": false,
"DataId": "Test01",
"Group": "20231019"
},
{
"Optional": false,
"DataId": "Test02",
"Group": "20231019"
},
{
"Optional": false,
"DataId": "Test03",
"Group": "20231020"
}
],
"Optional": false,
"Namespace": "ec934a6e-36f5-4f1a-90f4-b74824da42a2",
"ServerAddresses": [ "http://127.0.0.1:8848/" ]
}
分别获取三个配置项中的配置
[HttpGet]
[Route("GetConfig")]
public string GetConfig()
{
var Test01 = _configuration["Name"];
var Test02 = _configuration["Name2"];
var Test03 = _configuration["Address"];
return "Test01: "+Test01 + " "+"Test02:"+Test02 + " "+"Test03:" +Test03;
}