1、安装nuget包
2、加上配置文件
"nacos": {
"ServerAddresses": [ "http://127.0.0.1:8848" ],
"GroupName": "DEFAULT_GROUP",
"ClusterName": "DEFAULT",
"ServiceName": "webapi",
"DefaultTimeOut": 5000,
"Namespace": "public",
"Password": "nacos",
"UserName": "nacos",
"ListenInterval": 3000,
"ConfigUseRpc": false,
"NamingUseRpc": false,
"Listeners": [
{
"Group": "DEFAULT_GROUP",
"DataId": "webapi",
"Optional": false
}
]
}
注意:
"ConfigUseRpc": false
"NamingUseRpc": false
http连接选false否则配置中心可能会获取不到内容
3、注册
//注册nacos
builder.Services.AddNacosAspNet(builder.Configuration);
启动后
4、使用服务发现
/// <summary>
/// 服务发现-调用
/// </summary>
/// <returns></returns>
[HttpPost("find")]
public async Task<string> Find([FromServices] INacosNamingService nacosNaming)
{
Instance instance = await nacosNaming.SelectOneHealthyInstance("webapi", "DEFAULT_GROUP");
string ip = instance.GetIpPort();
HttpTool tool = new HttpTool();
string str = await tool.PostSendMessage($"http://{ip}/nacos/get", string.Empty);
return str;
}
/// <summary>
/// 得到ip和端口
/// </summary>
/// <param name="instance"></param>
/// <returns></returns>
public static string GetIpPort(this Instance instance)
{
return $"{instance.Ip}:{instance.Port}";
}
5、注册配置中心
//配置中心
builder.Services.AddNacosV2Config(builder.Configuration);
随意添加配置
6、使用配置中心
/// <summary>
/// 配置中心
/// </summary>
/// <param name="nacosConfig"></param>
/// <returns></returns>
[HttpPost("config")]
public async Task<string> GetConfig([FromServices] INacosConfigService nacosConfigService)
{
string str = nacosConfigService?.GetConfigAndSignListener("test", "DEFAULT_GROUP", 3000, new Tools.ConfigListener()).Result ?? "";
NacosTool? nacosTool = str.JsonTo<NacosTool>();
return "ok";
}
7、配置变化的监听方法,结合第6点
/// <summary>
/// 配置变化监听
/// </summary>
public class ConfigListener : IListener
{
/// <summary>
/// 监听方法
/// </summary>
/// <param name="configInfo"></param>
public void ReceiveConfigInfo(string configInfo)
{
Trace.WriteLine("接收到配置变化信息");
}
}
然后自由发挥吧