首页 > 其他分享 >Net6.0 集成 Nacos

Net6.0 集成 Nacos

时间:2023-08-15 18:25:49浏览次数:31  
标签:集成 builder Nacos options Services using Configuration Net6.0

1-创建一个 WebApi

2- 添加引用

Install-Package nacos-sdk-csharp -Version 1.3.5
Install-Package nacos-sdk-csharp.AspNetCore -Version 1.3.5
Install-Package nacos-sdk-csharp.Extensions.Configuration -Version 1.3.5

3- 设置 appsettings.json

{
  "Nacos": {
    "Listeners": [ //对应配置文件
      {
        "Optional": false,
        "DataId": "common", //配置名称
        "Group": "DEFAULT_GROUP" //组名
      },
      {
        "Optional": false,
        "DataId": "user",
        "Group": "DEFAULT_GROUP"
      }
    ],
    "DefaultTimeOut": 15,
    "ListenInterval": 1000,
    "ServiceName": "userApiSrv", //服务名称
    "Namespace": "public", //对应的是命名空间的Id
    "ServerAddresses": [ "http://ip地址:8848/" ], //是Nacos的服务器地址,可以添加多个
    "UserName": "nacos",
    "Password": "1Q2w3e4r$",
    "ConfigUseRpc": false, //false-http协议,true-grpc
    "NamingUseRpc": false //false-http协议,true-grpc
  },
  "Urls": "http://*:5101"
}

  4- nacos 服务配置配置

 

{
    "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.Async", "Serilog.Sinks.File" ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Information",
        "System": "Information"
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
    "Properties": {
      "ApplicationName": "GR.Nacos"
    },
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          "path": "Logs/log.log",
          "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog",
          "rollingInterval": "Day",
          "shared": true,
          "rollOnFileSizeLimit": true,
          "fileSizeLimitBytes": 102400000,
          "retainedFileCountLimit": 365,
          "outputTemplate": "{NewLine}{NewLine}Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel:{Level}{NewLine}Message:{Message}{NewLine}{Exception}"
        }
      },
      {
        "Name": "Seq",
        "Args": {
          "serverUrl": "http://localhost:8081"
        }
      }
    ]
  },
  "AllowedHosts": "*"
}

  

 

 5-程序配置

using Serilog;
using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using MicroSrv.User.HostApi.JSON;
using Kinwong.Logger;
using Kinwong.Swagger.NSwag;
using Nacos.AspNetCore.V2;
using Nacos.V2.DependencyInjection;
using MicroSrv.User.HostApi.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddNacosAspNet(builder.Configuration, section: "Nacos");
builder.Services.Configure<UserInfo>(builder.Configuration.GetSection("UserInfo"));
builder.Host.UseNacosConfig("Nacos", logAction: x => x.AddSerilog());
builder.Services.AddOptions();
//builder.Services.AddNacosWeb(builder.Configuration, builder.Configuration, section: "Nacos");
var _myAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Host.UseSerilog((context, services, logger) =>
{
    logger.ReadFrom.Configuration(context.Configuration)
          .ReadFrom.Services(services);
    logger.Enrich.FromLogContext();
});
builder.Services.Configure<ApiBehaviorOptions>(options =>
{
    //禁用自定义验证
    options.SuppressModelStateInvalidFilter = true;

    //options.InvalidModelStateResponseFactory = context =>
    //{
    //    var error = context.ModelState.GetValidationSummary();
    //    ////自定义自己想要返回的数据结果,我这里要返回的是Json对象,通过引用Newtonsoft.Json库进行转换
    //    var payload = JsonConvert.SerializeObject(Result.Error(HttpStatusCode.BadRequest.ToCode(), error));
    //    //////自定义返回的数据类型
    //    //context.HttpContext.Response.ContentType = "application/json";
    //    //////自定义返回状态码,默认为401 我这里改成 200
    //    //context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
    //    //////context.Response.StatusCode = StatusCodes.Status401Unauthorized;
    //    //////输出Json数据结果
    //    //context.HttpContext.Response.WriteAsync(payload);
    //    return new ObjectResult(error);
    //};
});
builder.Services.AddHttpContextAccessor();
builder.Services.AddCors(c =>
{
    //https://learn.microsoft.com/zh-cn/aspnet/core/security/cors?view=aspnetcore-6.0
    var cors = builder.Configuration.GetSection("Cors").Value;
    if (!string.IsNullOrWhiteSpace(cors))
    {
        c.AddPolicy(_myAllowSpecificOrigins, policy =>
        {
            policy.WithOrigins(cors.Split(','))
                .AllowAnyMethod()
                .AllowAnyHeader();
        });
    }
    else
    {
        c.AddPolicy(_myAllowSpecificOrigins, policy =>
        {
            policy.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
        });
    }
});
builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        //https://learn.microsoft.com/zh-cn/aspnet/core/web-api/advanced/formatting?view=aspnetcore-6.0
        //配置 小写 格式,而不是默认的 camelCase 格式
        options.JsonSerializerOptions.PropertyNamingPolicy = new LowercasePolicy();
        //中文转义处理
        options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
        //忽略大小写
        options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
    });
builder.Services.AddNSwagger(title: "User系统API接口文档", description: "API接口说明文档", contact: new NSwag.OpenApiContact { Url = "", Name = "" });


var app = builder.Build();
app.UseSerilogRequestLogging();
app.UseNSwagger();
app.UseAuthentication();
app.UseAuthorization();
// Configure the HTTP request pipeline.
app.MapControllers();
app.Run();

    主要配置:

builder.Services.AddNacosAspNet(builder.Configuration, section: "Nacos");
builder.Host.UseNacosConfig("Nacos", logAction: x => x.AddSerilog());

 PS:注意一下,我看了很多文档都说,直接使用IConfiguration 文件的 Get 就能获取的 nacos 的配置,这个是错误的,反正我这边测试是行不通的,必须使用 builder.Services.Configure<UserInfo>(builder.Configuration.GetSection("UserInfo"));  然后用  IOptions<UserInfo> options 才能拿到值,错误范例如下

 

 

 

6-创建一个控制器,开始使用nacos配置

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using MicroSrv.User.HostApi.Models;
using Nacos.V2;
using System.Diagnostics;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace MicroSrv.User.HostApi.Controllers
{
    /// <summary>
    /// 配置
    /// </summary>
    [Route("api/v{version:apiVersion}/[controller]")]
    [ApiController]
    public class ConfigController : ControllerBase
    {
        private IConfiguration _configuration;
        private readonly INacosConfigService _nacosConfigSrv;
        private readonly UserInfo _user;
        private readonly UserInfo _user2;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="nacosConfigSrv"></param>
        /// <param name="options"></param>
        /// <param name="optionsSnapshot"></param>
        public ConfigController(IConfiguration configuration
            , INacosConfigService nacosConfigSrv
            , IOptions<UserInfo> options
            , IOptionsSnapshot<UserInfo> optionsSnapshot)
        {
            _configuration = configuration;
            _nacosConfigSrv = nacosConfigSrv;
            _user = options.Value;
            _user2 = optionsSnapshot.Value;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<string> Get(int id)
        {
            string config = "";
            switch (id)
            {
                case 1:
                    var sconfig = _configuration.GetSection("Serilog");
                    config = sconfig["Using"];
                    break;
                case 2:
                    config = string.Format("old-{0},new-{1}", System.Text.Json.JsonSerializer.Serialize(_user), System.Text.Json.JsonSerializer.Serialize(_user2));
                    break;
                default:
                    config = await _nacosConfigSrv.GetConfig("common", Nacos.V2.Common.Constants.DEFAULT_GROUP, 3000);
                    break;
            }
            return config;
        }

    }
}

  

 

标签:集成,builder,Nacos,options,Services,using,Configuration,Net6.0
From: https://www.cnblogs.com/ganqiyin/p/17632058.html

相关文章

  • Net6.0 集成 支持 Nacos 的 Ocelot 网关
    1-创建Ocelot网关webapi 2-添加引用https://www.cnblogs.com/wucy/p/13353824.htmlInstall-Packagenacos-sdk-csharp-Version1.3.5Install-PackageOcelot.Provider.Nacos-Version1.3.5Install-PackageOcelot.Provider.Polly-Version1.3.53-配置appset......
  • Nacos v2.2.3 安装
    文档:https://nacos.io/zh-cn/docs/deployment.html1-安装nacos1.1-解压tar-zxvfnacos-server-2.2.3.tar.gz-C/usr/local1.2-开启鉴权cd/usr/local/nacos/confvimapplication.properties开启鉴权#nacos.core.auth.enabled=false#改成nacos.core.aut......
  • springboot 整合sentinel 和nacos实现流量控制
    方案一使用sentinel控制面板1、启动sentineljava-jarsentinel.jar2、在自己应用user中添加依赖<modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-pa......
  • nacos 单机3节点 集群env
     集群中包含3个NacosServer节点,两个Proxy主备节点,Mysql数据库主备这里仅记录Nacos的安装Nacos节点服务器节点IP端口Nacos1172.17.10.218858(默认8848)Nacos1172.17.10.228858(默认8848)Nacos1172.17.10.238858(默认8848)Nacos集群配置安装JAVA环......
  • SpringBoot3集成Redis
    目录一、简介二、工程搭建1、工程结构2、依赖管理3、Redis配置三、Redis用法1、环境搭建2、数据类型3、加锁机制四、Mybatis缓存1、基础配置2、自定义实现五、参考源码标签:Redis.Mybatis.Lock;一、简介缓存在项目开发中,基本上是必选组件之一,Redis作为一个key-value存储系统,具......
  • Nacos2 + Mysql8 作为数据源的建表语句
    在MySQL中创建nacos用户,MySQL创建名为Nacos的Schema,并授权nacos用户可以访问。语句如下:mysql>createuser'nacos'@'%'identifiedby'password';mysql>createschemanacos;mysql>grantALLonnacos.*to'nacos'@'%';或者直接新建一个n......
  • nacos集群部署
    准备nacos一般集群需要至少3个节点。我们先准备3台机器: 192.168.11.200、192.168.11.196、192.168.11.126nacos的默认服务端口是8848,但是由于我们的机器上还有其他nacos服务正在作用,所以,我们这里把端口改为8748,如下:192.168.11.200:8748192.168.11.196:8748192.168.11.......
  • 2-04-Nacos配置管理-配置热更新-not practice
    所谓的热更新共有两种实现方式1.@Value+@Refresh针对单一类的配置热更新2.@ConfigurationProperties+@Autowired,针对所有类的配置热更新......
  • 2-05-Nacos配置管理-多环境配置共享-not practice
    单环境配置文件-${spring.application.name}-${spring.profiles.active}.yaml多环境配置文件-${spring.application.name}.yaml配置优先级:${spring.application.name}-${spring.profiles.active}.yaml>-${spring.application.name}.yaml>本地.yaml怀疑-待测:远程的两个可能......
  • Visual Studio 的集成开发环境
    集成开发环境(IDE): 最重要的特点之一是将所有开发活动整合到一个界面中,使开发者能够在一个工具中完成编码、调试、测试和部署等多个任务。集成性(Integration): VisualStudio将多个开发工具和流程整合到一个界面中,使开发者能够更加高效地进行软件开发。多语言支持(Multi-LanguageS......