一、配置管理
1.添加一个新的命名空间
这里我都填写为publicdemo
2.C#代码配置启动
appsetting.json加上:
(nacos默认是8848端口)
"NacosConfig": {"ServerAddresses": [ "http://localhost:8848" ], // Nacos 服务器地址"Namespace": "publicdemo" // 命名空间}
startup.cs加上(方式一和方式二任选):
public void ConfigureServices(IServiceCollection services)
{services.AddControllers();// 加载 Nacos 配置,启用 Nacos 服务发现//方式一: 需要先在appsetting.json中配置好services.AddNacosV2Config(Configuration, null, "NacosConfig");services.AddNacosV2Naming(Configuration, null, "NacosConfig");//方式二:直接将配置写在这里//services.AddNacosV2Config(x =>//{// x.ServerAddresses = new System.Collections.Generic.List<string> { "http://localhost:8848/" };// x.EndPoint = "";// x.Namespace = "publicdemo";//});//services.AddNacosV2Naming(x =>//{// x.ServerAddresses = new System.Collections.Generic.List<string> { "http://localhost:8848/" };// x.EndPoint = "";// x.Namespace = "publicdemo";//});
}
3.C#WebApi接口实现配置增加/查询/删除
这里设置我们的dataId、group、value!
namespace WebApplication1.Controllers
{[ApiController][Route("[controller]")]public class Demo{private readonly INacosConfigService _ns;public Demo(INacosConfigService ns){_ns = ns;}[HttpPost][Route(nameof(PublishConfig))]public async Task<string> PublishConfig(INacosConfigService svc){var dataId = "demo-dateid";var group = "demo-group";var val = "test-value-" + DateTimeOffset.Now.ToString();await Task.Delay(500);var flag = await svc.PublishConfig(dataId, group, val);return $"发布配置结果,{flag}";}[HttpPost][Route(nameof(GetConfig))]public async Task<string> GetConfig(INacosConfigService svc){var dataId = "demo-dateid";var group = "demo-group";await Task.Delay(500);var config = await svc.GetConfig(dataId, group, 5000L);return $"获取配置结果,{config}";}[HttpPost][Route(nameof(RemoveConfig))]public async Task<string> RemoveConfig(INacosConfigService svc){var dataId = "demo-dateid";var group = "demo-group";await Task.Delay(500);var flag = await svc.RemoveConfig(dataId, group);return $"删除配置结果,{flag}";}/// <summary>/// 测试/// </summary>/// <returns></returns>[HttpPost][Route(nameof(GetInfoListAsync))]public async Task GetInfoListAsync(){await PublishConfig(_ns);await GetConfig(_ns);await RemoveConfig(_ns);}}
}
4.结果检验
选择正确的命名空间
找到我们的DataId,点击详情
5.操作总结
若需要还原为旧的配置,可在【历史版本】-【回滚】中操作
6.补充说明
1.用WebAPI增删改后,不重启情况下,可以利用WebAPI或UI界面查到最新数据
2.用UI界面增删改后,不重启情况下,可以利用WebAPI或UI界面查到最新数据
二、服务管理
1.服务的注册、查询、注销
[ApiController][Route("[controller]")]public class Demo{private readonly INacosConfigService _ns;public Demo(INacosConfigService ns){_ns = ns;}[HttpPost][Route(nameof(RegisterInstance))]public async Task<string> RegisterInstance(INacosNamingService svc, int port = 9999){await Task.Delay(500);var instace = new Nacos.V2.Naming.Dtos.Instance{ServiceName = "demo-svc1",ClusterName = Nacos.V2.Common.Constants.DEFAULT_CLUSTER_NAME,Ip = "127.0.0.1",Port = port,Enabled = true,Ephemeral = true,Healthy = true,Weight = 100,InstanceId = $"demo-svc1-127.0.0.1-{port}",Metadata = new System.Collections.Generic.Dictionary<string, string>{{ "m1", "v1" },{ "m2", "v2" },}};// 注册实例有很多重载,选适合自己的即可。await svc.RegisterInstance("demo-svc1", "DEFAULT_GROUP", instace);return $"注册实例成功";}[HttpPost][Route(nameof(GetAllInstances))]public async Task<string> GetAllInstances(INacosNamingService svc){await Task.Delay(500);// 获取全部实例有很多重载,选适合自己的即可。最后一个参数表明要不要订阅这个服务// SelectInstances, SelectOneHealthyInstance 是另外的方法可以获取服务信息。var list = await svc.GetAllInstances("demo-svc1", "DEFAULT_GROUP", false);return $"获取实例成功,{Newtonsoft.Json.JsonConvert.SerializeObject(list)}";}[HttpPost][Route(nameof(DeregisterInstance))]public async Task<string> DeregisterInstance(INacosNamingService svc){await Task.Delay(500);// 注销实例有很多重载,选适合自己的即可。await svc.DeregisterInstance("demo-svc1", "DEFAULT_GROUP", "127.0.0.1", 9999);return $"注销实例成功";}}
2.UI查询结果
3.功能效果
如果 WebAPI 宕机了,Nacos 会根据健康检查机制检测到该服务实例不可用,并将其从注册列表中移除。
4.自动注册
自动注册避免每次启动都需人工调用接口,提升服务管理效率,保证高可用性与灵活扩展,降低运维成本。
public class Startup
{public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){services.AddControllers();services.AddNacosV2Config(Configuration, null, "NacosConfig");services.AddNacosV2Naming(Configuration, null, "NacosConfig");}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}NacosAutoRegister(app);//增加这个方法app.UseRouting();app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapControllers();});}// 在应用启动时自动注册实例private void NacosAutoRegister(IApplicationBuilder app){var svc = app.ApplicationServices.GetRequiredService<INacosNamingService>();//获取服务var port = 9999;var instance = new Instance{ServiceName = "demo-svc1",ClusterName = Nacos.V2.Common.Constants.DEFAULT_CLUSTER_NAME,Ip = "127.0.0.1",Port = port,Enabled = true,Ephemeral = true,Healthy = true,Weight = 100,InstanceId = $"demo-svc1-127.0.0.1-{port}",Metadata = new Dictionary<string, string>{{ "m1", "v1" },{ "m2", "v2" }}};// 服务调用,自动注册实例svc.RegisterInstance("demo-svc1", "DEFAULT_GROUP", instance).Wait();}
}