3.在NET.API中去使用Nacos

nuget 安装:
1. nacos-sdk-csharp 1.3.4
2. nacos-sdk-csharp.AspNetCore 1.3.4
3. nacos-sdk-csharp.Extensions.Configuration 1.3.4

1.新建项目NacosService1,NacosService2,和NacosClient

配置NacosService1的appsettings.json,NacosService2也要配哈

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "nacos": {
    "ServerAddresses": [
      "http://127.0.0.1:8848"
    ],
    "DefaultTimeOut": 15000,//请求超时时间
    "Namespace": "6c0da0b7-eb66-4c15-b73e-15b983d07548",/命名空间id
    "ListenInterval": 1000,//监听间隔时间
    "ServiceName": "ServiceDiscovery.NacosService",//服务名称
    "GroupName": "DEFAULT_GROUP",// 默认分组名称
    "ClusterName": "DEFAULT",
    // 如果去掉这个配置项,系统会自动获取服务IP(建议去掉这个配置)
//     "Ip": "localhost",//注册中心,服务调用的IP地址
//     "PreferredNetworks": "localhost", //首选网络
//    // 如果去掉这个配置项,系统会自动获取服务运行的端口号(建议去掉这个配置)
//     "Port": 5199, // // 写0 表示80端口()
    "Weight": 100,
    "RegisterEnabled": true,
    "InstanceEnabled": true,
    "Ephemeral": true,
    "Secure": false,//表示当前服务是否时安全实例,用于标识访问的时候是否要启用 https
    "AccessKey": "",
    "SecretKey": "",
    "UserName": "",
    "Password": "",
    "ConfigUseRpc": false,
    "NamingUseRpc": false,
    "NamingLoadCacheAtStart": "",
    "LBStrategy": "WeightRandom",// 负载均衡策略:WeightRandom(随机), WeightRoundRobin(轮询)
    "Metadata": {
      "aa": "bb",
      "cc": "dd"
    }
  }
}

Program.cs配置

builder.Services.AddNacosAspNet(builder.Configuration,"nacos");

 

然后NacosService1,NacosService2创建控制器Controller,GetUsers方法里面的返回数据写不一样,等下方便检测。

[ApiController]
[Route("[controller]/[action]")]
public class UserController:ControllerBase
{
    [HttpGet]
    public List<UserInfo> GetUsers()
    {
        List<UserInfo> result = new()
        {
            new(){Id = 1,NickName = "张三"},
            new(){Id = 2,NickName = "李四"}
        };
        return result;
    }
}

注意哈,launchSettings.json内applicationUrl要改一下,不要写localhost

"http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "http://192.168.10.13:5199",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }

 

 

配置NacosClient的appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "nacos": {
    "ServerAddresses": [
      "http://127.0.0.1:8848"
    ],
    "DefaultTimeOut": 15000,//请求超时时间
    "Namespace": "6c0da0b7-eb66-4c15-b73e-15b983d07548",//命名空间id
    "ListenInterval": 1000,//监听间隔时间
    "ServiceName": "NacosClient",//服务名称
    "GroupName": "DEFAULT_GROUP", // 默认分组名称
    "ClusterName": "DEFAULT",
    // 如果去掉这个配置项,系统会自动获取服务IP(建议去掉这个配置)
//     "Ip": "localhost",//注册中心,服务调用的IP地址
//     "PreferredNetworks": "localhost", //首选网络
//    // 如果去掉这个配置项,系统会自动获取服务运行的端口号(建议去掉这个配置)
//     "Port": 5132, // // 写0 表示80端口()
    "Weight": 100,
    "RegisterEnabled": true,
    "InstanceEnabled": true,
    "Ephemeral": true,
    "Secure": false,//表示当前服务是否时安全实例,用于标识访问的时候是否要启用 https
    "AccessKey": "",
    "SecretKey": "",
    "UserName": "",
    "Password": "",
    "ConfigUseRpc": false,
    "NamingUseRpc": false,
    "NamingLoadCacheAtStart": "",
    "LBStrategy": "WeightRandom",// 负载均衡策略:WeightRandom(随机), WeightRoundRobin(轮询)
    "Metadata": {
      "aa": "bb",
      "cc": "dd"
    }
  }
}

Program.cs配置

builder.Services.AddNacosAspNet(builder.Configuration,"nacos");

NacosClient的控制器内容

[ApiController]
[Route("[controller]/[action]")]
public class UserClientController:ControllerBase
{
    private readonly INacosNamingService _nacosNamingService;

    public UserClientController(INacosNamingService nacosNamingService)
    {
        _nacosNamingService = nacosNamingService;
    }

    [HttpGet]
    public async Task<IActionResult> InvokeUserList()
    {
        // 获取服务的实例(自带负载均衡)
        var instance = await _nacosNamingService.SelectOneHealthyInstance("ServiceDiscovery.NacosService");

        var host = $"{instance.Ip}:{instance.Port}";

        var baseUrl = instance.Metadata.TryGetValue("secure", out _) //放弃out输出
            ? $"https://{host}"
            : $"http://{host}";

        if (string.IsNullOrWhiteSpace(baseUrl))
        {
            return Ok("empty");
        }

        var url = $"{baseUrl}/user/GetUsers";

        using (HttpClient client = new HttpClient())
        {
            var result = await client.GetAsync(url);
            return Ok(await result.Content.ReadAsStringAsync());
        }
    }
    
}

 

posted @ 2024-02-14 09:46  野码  阅读(60)  评论(0编辑  收藏  举报