国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

Asp.net core中實現自動更新的Option的方法示例

2024-07-10 12:48:32
字體:
來源:轉載
供稿:網友

Asp.net core可以監視json、xml等配置文件的變化, 自動刷新內存中的配置內容, 但如果想每隔1秒從zookeeper、consul獲取最新的配置信息, 需要自己實現.

閱讀了 Asp.net core Document的Custom configuration provider, 得知只需要實現自己的IConfigurationSource和對應ConfigurationProvider即可

在這個示例中, 我建立了一個簡單的option, 只包含一個不斷變化的計數器變量.

public class RefreshableOptions{  public int IncreasementCount { get; set; }}

實現IConfigurationSource和對應ConfigurationProvider, 內部有一個timer模擬從外部獲取了最新的數據, 這里為簡單起見, 采用硬編碼的方式指定了option的路徑

public class AutoRefreshConfigurationSource : IConfigurationSource{  public IConfigurationProvider Build(IConfigurationBuilder builder)  {    return new AutoRefreshConfigurationProvider();  }}public class AutoRefreshConfigurationProvider : ConfigurationProvider{  private int count = 0;  private bool isChanged;  public AutoRefreshConfigurationProvider() : base()  {    Timer timer = new Timer(TimerCallback);    timer.Change(1000, 3000);  }  public override void Load()  {    var beforeData = Data;    // 這里采用硬編碼指定option的路徑    Data = new Dictionary<string, string>() { { "AutoRefreshOptions:IncreasementCount", count.ToString() } };    isChanged = IsDictionaryChanged(beforeData, Data);  }  private void TimerCallback(object state)  {    count++;    this.Load();    if (isChanged)    {      base.OnReload();//通知IConfiguration實例, 有參數發生了改變      isChanged = false;    }  }  //判斷兩個Idictionary是否有不同的幫助方法  private static bool IsDictionaryChanged(IDictionary<string, string> before, IDictionary<string, string> after)  {    if (before == null && after == null)    {      return false;    }    if ((before == null) != (after == null))    {      return true;    }    if (before.Count != after.Count)    {      return true;    }    var ignoreCaseBefore = new Dictionary<string, string>(before, StringComparer.OrdinalIgnoreCase);    foreach (var afterItemKey in after.Keys)    {      if (!ignoreCaseBefore.TryGetValue(afterItemKey, out var beforeItemValue))      {        return true;      }      if (beforeItemValue != after[afterItemKey])      {        return true;      }      ignoreCaseBefore.Remove(afterItemKey);    }    if (ignoreCaseBefore.Count > 0)    {      return true;    }    return false;  }}

實現擴展方法

public static class AutoRereshConfigurationExtensions{  public static IConfigurationBuilder AddAutoRereshConfiguration(this IConfigurationBuilder builder)  {    return builder.Add(new AutoRefreshConfigurationSource());  }}

使用方法

新建一個WebApi項目, 在Program.CreateWebHostBuilder中增加黃色部分

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 夹江县| 囊谦县| 类乌齐县| 合江县| 南靖县| 行唐县| 禹城市| 阿瓦提县| 南皮县| 海安县| 四平市| 黄大仙区| 玛多县| 龙井市| 鄢陵县| 农安县| 克什克腾旗| 哈尔滨市| 海兴县| 靖西县| 阜南县| 衡阳市| 姚安县| 沁水县| 崇阳县| 聂拉木县| 桓仁| 漾濞| 新乐市| 德阳市| 台州市| 武夷山市| 休宁县| 察雅县| 乐山市| 高陵县| 张家口市| 裕民县| 东乡| 西吉县| 雷山县|