You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
3.5 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Memory;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.Options;
namespace OptionsPattern.Sutdy.Experience.ConsoleApp
{
/// <summary>
/// 6.1.3 配置源的同步
/// 单独一个线程,随机时间改变配置文件内容
/// 主线程接收的更改通知,把新配置打印到控制台窗口
/// </summary>
internal class Program
{
private static string jsonConfigFile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"appsettings.json");
static void Main(string[] args)
{
Console.WriteLine("============ 配置选项编程体验6.1.3 配置源的同步 ============");
//获取配置项
var configuration=new ConfigurationBuilder().AddJsonFile(jsonConfigFile,false,true).Build();
new ServiceCollection()
.AddOptions()
.Configure<AppOption>(configuration)
.BuildServiceProvider()
.GetRequiredService<IOptionsMonitor<AppOption>>()
.OnChange(app =>
{
var jsonText = JsonSerializer.Serialize(app);
Console.WriteLine($"{DateTime.Now.ToString("yyyy:MM:dd HH:mm:ss FFFFFF")} 接到变更通知,新项为:");
Console.WriteLine(jsonText);
});
//随机改变配置文件内容
new Thread((jsonFile) =>
{
while (true)
{
ChangeJsonFileContent(jsonConfigFile, 5, 10);
}
})
.Start(jsonConfigFile);
Console.ReadLine();
}
/// <summary>
/// 随机秒数随机改变Json配置文件配置项的值
/// </summary>
static void ChangeJsonFileContent(string jsonFileFullPath,int min=5,int max = 20)
{
if (string.IsNullOrWhiteSpace(jsonFileFullPath))
{
throw new ArgumentException($"参数{nameof(jsonFileFullPath)}不能为空!");
}
if (!File.Exists(jsonFileFullPath))
{
throw new FileNotFoundException($"参数{nameof(jsonFileFullPath)}指定的json配置文件不存在");
}
//随机时间(秒数)
Random random = new Random();
var secondNum = random.Next(min, max);
Thread.Sleep(1000 * secondNum);
//读取Json配置文件内容
var appOption = new ConfigurationBuilder()
.AddJsonFile(jsonFileFullPath, false, false)
.Build()
.Get<AppOption>();
//改变配置项
appOption.AppName = Guid.NewGuid().ToString()+"_AppName";
appOption.AppVersion = new Version(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
appOption.EMail = new ReceiveMailOption()
{
ReceiveAddress = appOption.AppName + "@163.com",
Recipient = secondNum + "_Recipient",
};
//写回文件
var jsonText = JsonSerializer.Serialize(appOption);
File.WriteAllText(jsonFileFullPath,jsonText);
Console.WriteLine($"{DateTime.Now.ToString("yyyy:MM:dd HH:mm:ss FFFFFF")} 改变配置文件内容:");
Console.WriteLine(jsonText);
}
}
}