ocelot 配置文件的动态更新
本文意在通过ocelot 了解asp.net core 对配置文件的动态更新机制。
一 配置文件与对象绑定
UseOcelot方法调用时会执行配置文件对象创建,CreateConfiguration方法有个重要的对象 IOptionsMonitor<FileConfiguration> 通过
fileConfig.onchange 注册回调方法 更改存储库。实现对内存对象FileConfiguration 的更新。
public static async Task<IApplicationBuilder> UseOcelot(this IApplicationBuilder builder, OcelotPipelineConfiguration pipelineConfiguration) { var configuration = await CreateConfiguration(builder);
// ***
} private static async Task<IInternalConfiguration> CreateConfiguration(IApplicationBuilder builder) { // make configuration from file system? // earlier user needed to add ocelot files in startup configuration stuff, asp.net will map it to this var fileConfig = builder.ApplicationServices.GetService<IOptionsMonitor<FileConfiguration>>(); // now create the config // *** fileConfig.OnChange(async (config) => { var newInternalConfig = await internalConfigCreator.Create(config); internalConfigRepo.AddOrReplace(newInternalConfig.Data); }); }
先来看看IOptionsMonitor<T> 定义如下:
public interface IOptionsMonitor<out TOptions> { TOptions CurrentValue { get; } TOptions Get(string name); IDisposable OnChange(Action<TOptions, string> listener); }
IOptionsMonitor 从下面的服务注册可知 是OptionsMonitor<>
public static IServiceCollection AddOptions(this IServiceCollection services) {
// ***
services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptionsMonitor<>), typeof(OptionsMonitor<>)));return services; }
一 物理文件最终处理
public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((context, builder) => { builder.SetBasePath(context.HostingEnvironment.ContentRootPath) .AddJsonFile("Ocelot.json"); }) .UseUrls("http://localhost:6000") .UseStartup<Startup>() .Build();
webhost build的过程中都会绑定物理文件,如上的AddJsonFile。AddJsonFile的定义如下
public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange)
通过IFileProvider的实现,通过system.io对文件系统监控 实现最终的物理文件更改通知到上层。
二
作者:RunStone
出处:https://www.cnblogs.com/RunStone/p/9531159.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构