Asp.net core 에서 자동 으로 업데이트 되 는 Option 을 실현 하 는 방법 예시

Asp.net core 는 json,xml 등 프로필 의 변 화 를 감시 하고 메모리 의 설정 내용 을 자동 으로 새로 고 칠 수 있 습 니 다.그러나 1 초 마다 zookeeper,consul 에서 최신 설정 정 보 를 얻 으 려 면 스스로 실현 해 야 합 니 다.
Asp.net core DocumentCustom 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());
  }
}

사용 방법
Program.Create WebHostBuilder 에 노란색 부분 을 추가 하 는 WebApi 프로젝트 를 새로 만 듭 니 다.

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

Startup.Configure Services 에 설정

services.Configure<RefreshableOptions>(Configuration.GetSection("AutoRefreshOptions"));
ValuesController 수정

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

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

시작 후 끊임없이 새로 고침http://localhost:5000/api/values돌아 오 는 내용 의 변 화 를 볼 수 있 습 니 다.
본문 코드
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기