• NET6 IOptionsSnapshot 配合Apollo 实现动态配置 支持自定义解析


     

    1、Program.cs中注册配置Apollo

    builder.Host
        .ConfigureAppConfiguration((_, options) =>
        {
            options.AddConfigurationApollo("apolloSetting.json");
        });


    AddConfigurationApollo静态类

    复制代码
    public static class ConfigurationBuilderExtensions
    {
        /// 
        /// 接入Apollo
        /// 
        /// 
        /// 
        /// 
        public static void AddConfigurationApollo(this IConfigurationBuilder configurationBuilder, string jsonPath)
        {
            if (!string.IsNullOrEmpty(jsonPath))
                configurationBuilder.AddJsonFile(jsonPath, true, false);
    
            //阿波罗的日志级别调整
            LogManager.UseConsoleLogging(LogLevel.Warn);
            var options = new ApolloOptions();
    
            configurationBuilder.Build().Bind("Apollo", options);
    
            if (!options.Enable) return;
    
            var apolloBuilder = configurationBuilder.AddApollo(root.GetSection("Apollo:ApolloConfig")).AddDefault();
    
            foreach (var item in options.Namespaces)
            {
                apolloBuilder.AddNamespace(item.Name, ConfigFileFormat.Json);
            }
        }
        
    }
    复制代码

    apolloSetting.json配置文件

    复制代码
    {
      "Apollo": {
        "Enable": true,
        "ApolloConfig": {
          "AppId": "Rcp.Api",
          "Env": "DEV",
          "MetaServer": "http://127.0.0.1:8001",
          "ConfigServer": [ "http://127.0.0.1:8001" ]
        },
        "Namespaces": [
          {
            "Name": "xxxx",
            "Format": "json"
          }
        ]
      }
    }
    复制代码


    2、注册完毕以后,在Program.cs中自定义解析配置。AppSetting是Apollo配置中的Json对应的模型类。

    复制代码
    // 注册配置
    builder.Services.AddOptions()
        .Configure(builder.Configuration)
        .PostConfigure(option =>
        {
         // TODO 任何自定义解析操作 每次Apollo更新都会执行这里的自定义解析
         // 举例: option.AppConfig.ConnectionReadString
    = "123"; });
    复制代码

     

    3、在Program.cs中使用配置的方法

    var provider   = builder.Services.BuildServiceProvider();
    var appSetting = provider.GetRequiredService>().Value;

    这里拿到的 appSetting 对象 便是赋值之后的配置。 这里的前置条件是使用了依赖注入注册了服务。

    4、在控制器层/服务层/仓储层获取配置的方法,这里列举控制器层的使用方法

    复制代码
      // 
      private
    readonly AppSetting _appSetting;
      // 构造函数依赖注入配置 这里的重点是使用IOptionsSnapshot 程序每次收到请求的时候都会重新拉取配置文件,从而实现实时获取配置更新
      // IOptions是单例模式,创建后只能通过代码修改
      // IOptionsMonitor也是单例模式,它可以通过IOptionsChangeTokenSource 监测到配置文件更新,也能通过代码的方式更改值
      // IOptionsSnapshot是当前请求范围内创建,每次请求都是新的
      // PS 建议这一块内容多看看官方文档
      public AppSettingTestController(IOptionsSnapshot appOptionsSnapshot)   {     _appSetting = appOptionsSnapshot.Value;   }   ///   /// 获取配置文件测试   ///   ///   [HttpGet]   public AppSetting Get()   {     return _appSetting;   }
    复制代码

     

     
  • 相关阅读:
    古人的名与字、号、讳、谥有什么区别
    游戏缺失d3dx9_39.dll的5个修复方法,深度解析d3dx9_39.dll文件的作用
    hyperf框架聚合查询多字段查询
    前端项目如何找到所有未被引用的文件
    Web前端:面向程序员的五大前端技术
    tkinter控件样式
    24、四大函数式接口(有函数型接口和断定型接口(都是函数式接口))
    C++11 lambda
    访问者模式(大话设计模式)C/C++版本
    SpringCloud-2-入门概述
  • 原文地址:https://www.cnblogs.com/souphm/p/16670086.html