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

 

1、Program.cs中注册配置Apollo

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


AddConfigurationApollo静态类

public static class ConfigurationBuilderExtensions
{
    /// <summary>
    /// 接入Apollo
    /// </summary>
    /// <param name="builder"></param>
    /// <param name="jsonPath"></param>
    /// <param name="serviceCollection"></param>
    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<AppSetting>(builder.Configuration)
    .PostConfigure<AppSetting>(option =>
    {
     // TODO 任何自定义解析操作 每次Apollo更新都会执行这里的自定义解析
     // 举例: option.AppConfig.ConnectionReadString
= "123"; });

 

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

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

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

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

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

 

 
posted @ 2022-09-08 17:00  塔斯丁狗  阅读(337)  评论(0编辑  收藏  举报