1、說明
當一些配置需要修改在進行獲取時,通常做法是修改完配置文件后再重啟web服務器或者docker進行完成,下面我介紹一種熱更新方法,修改完配置文件后,不需要重啟服務器即可獲取最新的配置文件,讓服務感知配置的變化。
2、實踐
下面我通過二種方式來講解一下.Net Core實現選擇數據熱更新,讓服務感知配置的變化。
2.1 通過AddSingleton單例方式注入,然后使用 IOptionsMonitor實現數據熱更新
2.1.1 首先在Startup.cs文件中的ConfigureServices方法添加配置
//通過讀取配置文件加載到SystemPath類中 services.Configure<SystemPath>(Configuration.GetSection("SystemPath")); //添加服務注入 services.AddSingleton<IPathService, PathService>();
public class SystemPath { public string FilePath { get; set; } }
2.1.2 在PathService構造器中注入IOptionsMonitor<SystemPath>實現數據熱更新
public class PathService : IPathService { IOptionsMonitor<SystemPath> _options; /// <summary> /// 構造函數 /// </summary> /// <param name="blogData"></param> public PathService(IOptionsMonitor<SystemPath> options) { _options = options; } public string GetPath() { return _options.CurrentValue.FilePath; } }
2.1.3 在PathController中通過調用接口方式讀取最新配置路徑
/// <summary> /// 路徑 /// </summary> [Route("api/[controller]/[action]")] [ApiController] public class PathController : ControllerBase { private readonly IPathService _pathService; /// <summary> /// 構造函數 /// </summary> /// <param name="pathService"></param> public PathController(IPathService pathService) { _pathService = pathService; } /// <summary> /// 獲取系統路徑 /// </summary> /// <returns></returns> [HttpGet] public MethodResult GetSystemPath() { return new MethodResult(_pathService.GetPath()); } }
運行看一下效果:
現在讀取到的路徑是D:/File/2.jpg,我們修改一下配置文件然后重新調用接口看一下,這時會更新最新的路徑。
2.2 通過AddScoped 方式注入,然后使用 IOptionsSnapshot 實現數據熱更新
2.2.1 首先在Startup.cs文件中的ConfigureServices方法添加配置
//通過讀取配置文件加載到SystemPath類中 services.Configure<SystemPath>(Configuration.GetSection("SystemPath")); //添加服務注入 services.AddScoped<IPathService, PathService>();
public class SystemPath { public string FilePath { get; set; } }
2.2.2 在PathService構造器中注入IOptionsMonitor<SystemPath>實現數據熱更新
public class PathService : IPathService { IOptionsSnapshot<SystemPath> _options; /// <summary> /// 構造函數 /// </summary> /// <param name="blogData"></param> public PathService(IOptionsSnapshot<SystemPath> options) { _options = options; } public string GetPath() { return _options.Value.FilePath; } }
2.2.3 在PathController中通過調用接口方式讀取最新配置路徑
/// <summary> /// 路徑 /// </summary> [Route("api/[controller]/[action]")] [ApiController] public class PathController : ControllerBase { private readonly IPathService _pathService; /// <summary> /// 構造函數 /// </summary> /// <param name="pathService"></param> public PathController(IPathService pathService) { _pathService = pathService; } /// <summary> /// 獲取系統路徑 /// </summary> /// <returns></returns> [HttpGet] public MethodResult GetSystemPath() { return new MethodResult(_pathService.GetPath()); } }
運行看一下效果:
現在讀取到的路徑是D:/File/2.jpg,我們修改一下配置文件然后重新調用接口看一下,這時會更新最新的路徑。
到此這篇關于.Net Core實現選擇數據熱更新讓服務感知配置的變化的文章就介紹到這了,更多相關.Net Core數據熱更新內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.cnblogs.com/ZhengHengWU/p/13197820.html