应无所住,而生其心
排名
1
文章
860
粉丝
112
评论
163
net core webapi post传递参数
庸人 : 确实坑哈,我也是下班好了好几次,发现后台传递对象是可以的,但...
百度编辑器自定义模板
庸人 : 我建议换个编辑器,因为现在百度富文本已经停止维护了,用tinymec...
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术

.net6使用nacos实现服务注册与服务发现

8814人阅读 2022/12/25 17:22 总访问:5214408 评论:0 收藏:0 手机
分类: 微服务


.net6使用nacos作为配置中心:
https://www.tnblog.net/aojiancc2/article/details/7870
docker安装nacos v2.1.2:
https://www.tnblog.net/aojiancc2/article/details/7865
nacos的官方文档:
https://nacos.io/zh-cn/docs/v2/quickstart/quick-start.html
.net 的sdk
https://github.com/nacos-group/nacos-sdk-csharp
nacos下.net的驱动地址:
https://github.com/nacos-group/nacos-sdk-csharp

.net6使用nacos服务注册

第一步,添加依赖库

  1. <PackageReference Include="nacos-sdk-csharp" Version="1.3.4" />
  2. <PackageReference Include="nacos-sdk-csharp.AspNetCore" Version="1.3.4" />
  3. <PackageReference Include="nacos-sdk-csharp.Extensions.Configuration" Version="1.3.4" />
  4. <PackageReference Include="nacos-sdk-csharp.IniParser" Version="1.3.4" />
  5. <PackageReference Include="nacos-sdk-csharp.YamlParser" Version="1.3.4" />

第二步,在appsettings.json中配置好使用nacos的信息

  1. "nacos": {
  2. "EndPoint": "",
  3. "ServerAddresses": [ "nacos服务地址" ],
  4. "DefaultTimeOut": 15000,
  5. //常用场景之一是不同环境的注册的区分隔离,例如开发测试环境和生产环境的资源(如配置、服务)隔离等。
  6. "Namespace": "public", //服务注册到的命名空间,不能乱填,否者注册不上的
  7. "ListenInterval": 1000,
  8. "ServiceName": "BaseApi", //服务名称
  9. "GroupName": "DEFAULT_GROUP", //服务分组
  10. "ClusterName": "DEFAULT",
  11. "Ip": "",
  12. "PreferredNetworks": "", // select an IP that matches the prefix as the service registration IP
  13. "Port": 8805,//端口,如果设置为0就自动获取项目的端口
  14. "Weight": 100, // 权重
  15. "RegisterEnabled": true,
  16. "InstanceEnabled": true,
  17. "Ephemeral": true,
  18. "Secure": false,
  19. "AccessKey": "",
  20. "SecretKey": "",
  21. "UserName": "nacos",
  22. "Password": "nacos",
  23. "ConfigUseRpc": true, // 为true时,通过 gRPC 去和 nacos server 交互,nacos 2.x版本要设置为true": null,
  24. "NamingUseRpc": true, // 为true时,通过 gRPC 去和 nacos server 交互, nacos 2.x版本要设置为true": null,
  25. "NamingLoadCacheAtStart": "",
  26. "LBStrategy": "WeightRandom", //WeightRandom WeightRoundRobin
  27. "Metadata": {
  28. "aa": "bb",
  29. "cc": "dd"
  30. }
  31. }

最主要就是nacos服务的地址,登录nacos的账户与密码,以及服务名,服务分组等。

第三步,在Program.cs中去加入nacos的服务注册

  1. //nacos服务注册
  2. builder.Services.AddNacosAspNet(builder.Configuration);

做好以上步骤,启动一下项目就可以在nacos看到注册的服务了。

点击服务详情可以看到,服务的ip地址,端口号,元数据,等信息。

.net6使用nacos服务发现

很简单使用INacosNamingService即可。直接贴代码

  1. using Microsoft.AspNetCore.Mvc;
  2. namespace NacosLearn.Controllers
  3. {
  4. [ApiController]
  5. [Route("api/[controller]")]
  6. public class WeatherForecastController : ControllerBase
  7. {
  8. private readonly IConfiguration _configuration;
  9. private readonly ILogger<WeatherForecastController> _logger;
  10. private readonly Nacos.V2.INacosNamingService _svc;
  11. public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration, Nacos.V2.INacosNamingService svc)
  12. {
  13. _logger = logger;
  14. _configuration = configuration;
  15. _svc = svc;
  16. }
  17. [HttpGet]
  18. public IEnumerable<string> Get()
  19. {
  20. var dbConfig = _configuration.GetSection("DbConfig");
  21. //读取连接字符串配置
  22. string connectionString = dbConfig["ConnectionString"];
  23. //读取配置
  24. string isAutoCloseConnection = _configuration["DbConfig:IsAutoCloseConnection"];
  25. //读取common里边的配置
  26. string UserName = _configuration["UserName"];
  27. string Password = _configuration["Password"];
  28. return new List<string>() { connectionString, isAutoCloseConnection };
  29. }
  30. /// <summary>
  31. /// 通过nacos的服务发现来调用接口
  32. /// </summary>
  33. /// <returns></returns>
  34. [HttpGet("test")]
  35. public async Task<string> Test()
  36. {
  37. // 通过分组与服务名获取
  38. var instance = await _svc.SelectOneHealthyInstance("BaseApi", "DEFAULT_GROUP");
  39. var host = $"{instance.Ip}:{instance.Port}";
  40. var baseUrl = instance.Metadata.TryGetValue("secure", out _)
  41. ? $"https://{host}"
  42. : $"http://{host}";
  43. if (string.IsNullOrWhiteSpace(baseUrl))
  44. {
  45. return "empty";
  46. }
  47. //测试调用一下上面那个接口
  48. var url = $"{baseUrl}/api/WeatherForecast";
  49. using (HttpClient client = new HttpClient())
  50. {
  51. var result = await client.GetAsync(url);
  52. return await result.Content.ReadAsStringAsync();
  53. }
  54. }
  55. //[HttpGet(Name = "GetWeatherForecast")]
  56. //public IEnumerable<WeatherForecast> Get()
  57. //{
  58. // return Enumerable.Range(1, 5).Select(index => new WeatherForecast
  59. // {
  60. // Date = DateTime.Now.AddDays(index),
  61. // TemperatureC = Random.Shared.Next(-20, 55),
  62. // Summary = Summaries[Random.Shared.Next(Summaries.Length)]
  63. // })
  64. // .ToArray();
  65. //}
  66. }
  67. }

怎么动态的注入服务到不同的地方,比如动态切换生产环境与本地开发环境

非常简单,开发环境一个配置,生成环境一个配置,根据环境变量进行加载就行。和使用nacos作为配置中心根据不通情况读取配置一个道理

  1. //获取环境变量。可以环境变量的不同去读取不同naocs服务的配置
  2. string environmentName = builder.Environment.EnvironmentName;
  3. builder.Services.AddNacosAspNet(builder.Configuration, "nacos" + environmentName);

builder.Services.AddNacosAspNet方法也是可以传递配置节点的,当然可以动态的来加载


欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739。有需要软件开发,或者学习软件技术的朋友可以和我联系~(Q:815170684)

评价

.net6 Ocelot 与 Kubernetes

.Net6 Ocelot 与 Kubernetes[TOC] 前言这玩意太坑人了。浪费了我一天的时间。先看我们想实现的效果流程: 首先我们请求sv...

.net core发布出来swagger无法访问。docker 发布.net6 webapi swagger访问不到

因为代码里边设置swagger的代码是: if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.Use...

.net6 指定时区

.Net6 指定时区[TOC] 最近相当忙!忙着学这学那的,各种考试。以及项目上也有很多改动。还有这恶心的时间问题(特别注意当...

.net6 AsyncEx 异步锁

.Net6 AsyncEx[TOC] 简单来讲就是可以通过异步方式实现锁。安装&lt;PackageReference Include=&quot;Nito.AsyncEx&quot; V...

Kubernetes .net6 集群管理(一)

Kubernetes .Net6 集群管理(一)[TOC] 对于Kubernetes集群的管理,.net提供了KubernetesClient库,可以对k8s集群通过简单...

Kubernetes .net6 Webhook

Kubernetes .Net6 Webhook[TOC] 本文主要是学习陈计节大佬讲的 使用 .NET Core 开发 Kubernetes 基础组件记录的笔记。 Ad...

.net6 设置信任自签证书(浏览器可信任)

.Net6 设置信任自签证书(浏览器可信任)[TOC] 先决条件确保本地windows上拥有openssl,没有的自己去:http://slproweb.com...

Kubernetes .net6 CRD

Kubernetes .Net6 CRD[TOC] CRD介绍简单来说就是自定义资源,像Pod、Service、Deployment一样。创建自定义资源的资源类型...

linux批量执行命令脚本。linux脚本执行docker镜像打包运行.net6项目等

linux批量执行命令脚本1:创建一个.sh后缀的文件vi run.sh 2:在文件开头添加内容#!/bin/bash 3:在文件里边输入想要执行...

docker发布.net6项目。制作发布的批量脚本一键发布脚本

docker 发布.net core项目可以参考:https://www.tnblog.net/aojiancc2/article/details/5030 docker发布.net6项目简单的d...

.net6 连接mysql报错Unable to connect to any of the specified MySQL hosts.

.net5/6 连接mysql报错Unable to connect to any of the specified MySQL hosts. 不能使用点.连接 server=.;uid=root;pwd...

.net6使用nacos作为配置中心

consul+.net core实现配置中心:https://www.tnblog.net/aojiancc2/article/details/6815nacos的安装参考:https://www.tnbl...

.net6使用session

先在Program.cs中引入 使用存储 HttpContext.Session.SetString(&quot;nickname&quot;,&quot;test&quot;); 读取 string...

.net6.net core获取服务器上所有网卡的IP地址

代码如下: //获取服务器上所有网卡的IP地址 NetworkInterface[] networks = NetworkInterface.GetAllNetworkInterfaces(...

.net6使用nacos 集群部署,负载均衡调用 。docker swarm 集群部署.net6项目

我们这里的k8s测试环境暂时用不了了,这里先使用docker swarm来进行一下集群部署。.net6使用nacos实现服务注册与服务发现:h...