如何在Asp.netcore中实现自动更新Option-创新互联

如何在Asp.net core中实现自动更新Option?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

创新互联是一家专业提供正定企业网站建设,专注与成都做网站、成都网站设计、HTML5、小程序制作等业务。10年已为正定众多企业、政府机构等服务。创新互联专业的建站公司优惠进行中。

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() { { "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 before, IDictionary 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(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中增加黄色部分

WebHost.CreateDefaultBuilder(args)
  .ConfigureAppConfiguration(config =>
  {
    config.AddAutoRereshConfiguration();
  })
  .UseStartup();

在Startup. ConfigureServices中配置

services.Configure(Configuration.GetSection("AutoRefreshOptions"));

修改ValuesController

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
  private RefreshableOptions refreshableOptions;
  public ValuesController(IOptionsSnapshot refreshableOptions)
  {
    this.refreshableOptions = refreshableOptions.Value;
  }

  [HttpGet]
  public ActionResult> Get()
  {
    return new string[] { "value1", "value2", refreshableOptions.IncreasementCount.ToString() };
  }
}

ASP.NET 是什么

ASP.NET 是开源,跨平台,高性能,轻量级的 Web 应用构建框架,常用于通过 HTML、CSS、JavaScript 以及服务器脚本来构建网页和网站。

看完上述内容,你们掌握如何在Asp.net core中实现自动更新Option的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!


当前题目:如何在Asp.netcore中实现自动更新Option-创新互联
当前链接:http://scyanting.com/article/dogphe.html