出处:https://www.cnblogs.com/buruainiaaaa/p/14121176.html
作者:唐@
最近一段时间 因公司业务需要,需要使用.net5做一套微服务的接口,使用nacos 做注册中心和配置中心,ocelot做网关。
因为ocelot 支持的是consol和eureka,如果使用nacos做服务发现,需要自己集成,以此记录下
Nacos 支持基于 DNS 和基于 RPC 的服务发现(可以作为注册中心)、动态配置服务(可以做配置中心)、动态 DNS 服务。官网地址:https://nacos.io/en-us/
ocelot 相信大家都比较熟悉,官网:https://ocelot.readthedocs.io/en/latest/index.html
环境安装:
nacos参考地址:https://blog.csdn.net/ooyhao/article/details/102744904
基于.net版本的nacos sdk:nacos-sdk-csharp-unofficial.AspNetCore (此处有坑 :Nacos.AspNetCore 已经停止更新,代码已迁移,服务注册会有问题)
SDK源码地址:https://github.com/catcherwong/nacos-sdk-csharp
配置中心:
1.在nacos添加配置
2.在.net 项目中 配置文件中 添加相关配置
1 "nacos": {
2 "ServerAddresses": [ "http://127.0.0.1:8849/" ], 3 "DefaultTimeOut": 30000, 4 "Namespace": "", 5 "ListenInterval": 30000, 6 "ServiceName": "ServiceName",
"RegisterEnabled": true, 7 "Weight": 10 8 }, 9 "nacosData": {
10 "DataId": "nacosConfig",11 "Group": "Pro"12 }
3.在Startup.cs添加nacos sdk的DI注册
1 services.AddNacos(Configuration);
4.创建AppConfig类,定义构造函数:(从DI中获取INacosConfigClient对象)
public AppConfig(IServiceCollection _services, IConfiguration _configuration)
{
services = _services;
configuration = _configuration;var serviceProvider = services.BuildServiceProvider();
_configClient = serviceProvider.GetService();
}
5.添加LoadConfig方法,加载配置中心的配置
代码说明:sectionKey入参 为配置文件中的key(nacosData),responseJson为配置中心的完整配置字符串,可以是json,可以是key=value模式,根据字符串格式,转为Dictionary中,放入静态私有对象中
/// /// 加载nacos配置中心/// /// private async Task LoadConfig(string sectionKey)
{
try
{
GetConfigRequest configRequest = configuration.GetSection(sectionKey).Get();if (configRequest == null || string.IsNullOrEmpty(configRequest.DataId))
{
return;
}var responseJson = await _configClient.GetConfigAsync(configRequest);
Console.WriteLine(responseJson);if (string.IsNullOrEmpty(responseJson))
{
return;
}var dic = LoadDictionary(responseJson);if (sectionKey == commonNacosKey)
{
commonConfig = dic;