nacos启动不能发现服务_.net5+nacos+ocelot 配置中心和服务发现实现

出处: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添加配置

44576f62f1277b7dde74bfdb2245bf7d.png

    2.在.net 项目中 配置文件中 添加相关配置

680ca6fa401637e9ce3ef11ef94e1568.png

 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 }

680ca6fa401637e9ce3ef11ef94e1568.png

3.在Startup.cs添加nacos  sdk的DI注册

1 services.AddNacos(Configuration);

 4.创建AppConfig类,定义构造函数:(从DI中获取INacosConfigClient对象)

680ca6fa401637e9ce3ef11ef94e1568.png

 public AppConfig(IServiceCollection _services, IConfiguration _configuration)
{
services = _services;
configuration = _configuration;var serviceProvider = services.BuildServiceProvider();
_configClient = serviceProvider.GetService();
}

680ca6fa401637e9ce3ef11ef94e1568.png

5.添加LoadConfig方法,加载配置中心的配置

代码说明:sectionKey入参 为配置文件中的key(nacosData),responseJson为配置中心的完整配置字符串,可以是json,可以是key=value模式,根据字符串格式,转为Dictionary中,放入静态私有对象中

680ca6fa401637e9ce3ef11ef94e1568.png

/// /// 加载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;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值