未使用IOptionsSnapshot或IOptionsMonitor(使用.net6和Worker Service模板)获取更新的配置状态。
我已经开始在.net6中使用Workers进行测试。
我的问题是,我一直在配置设置中工作,一切都很好。。。直到我需要获得配置文件的更新状态以延迟或继续我的Worker必须执行的进程。
这是我的代码文件:
程序.cs
var builder = Host.CreateDefaultBuilder();
// Config
builder.ConfigureAppConfiguration((hostBuilderContext, configurationBuilder) =>
{
configurationBuilder.AddJsonFile(
ConfigurationConstants.AppSettingsFileLocation,
optional: false,
reloadOnChange: true
);
var env = hostBuilderContext.HostingEnvironment;
configurationBuilder
.AddJsonFile(
ConfigurationConstants.AppSettingsFileLocation,
optional: false,
reloadOnChange: true
)
.AddJsonFile(
$"./Configuration/environments/environment.{env.EnvironmentName}.json",
optional: false,
reloadOnChange: true
);
var configuration = configurationBuilder.Build();
});
// Services
builder.ConfigureServices((hostBuilderContext, services) =>
{
services.AddHostedService<Worker>();
services.AddScoped<MessageRouterProcess, MessageRouterProcess>();
services.AddTransient<IQueueManager, RabbitMQQueueManagerAdapter>();
services.Configure<WorkerConfiguration>(hostBuilderContext.Configuration.GetSection(nameof(WorkerConfiguration)));
});
var host = builder.Build();
await host.RunAsync();
Worker.cs
这将运行业务逻辑服务,即“MessageRouterProcess.cs”
namespace Meloons.Whatsapp.Worker.MessageRouter
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public IServiceProvider Services { get; }
public Worker(
IServiceProvider serviceProvider,
ILogger<Worker> logger
)
{
Services = serviceProvider;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Consume Scoped Service Hosted Service running.");
await DoWork(stoppingToken);
}
private async Task DoWork(CancellationToken stoppingToken)
{
_logger.LogInformation("Consume Scoped Service Hosted Service is working.");
using (var scope = Services.CreateScope())
{
var scopedProcessingService =
scope.ServiceProvider
.GetRequiredService<MessageRouterProcess>();
await scopedProcessingService.RouteMessages();
}
}
}
}
业务逻辑
MessageRouterProcess.cs
在这个文件中,在while循环中,我有这样的验证:“if(!this.Configuration.Lecture)”。
这会得到一个Config值,基于这个值,我的工作人员将延迟并跳过循环的当前迭代(这样业务逻辑就不会执行),或者将运行所有流程。
namespace Meloons.Whatsapp.WebAPI.Core
{
public class MessageRouterProcess
{
protected WorkerConfiguration Configuration;
private IQueueManager queueManager;
private readonly HttpClient _httpClient;
public MessageRouterProcess(
IQueueManager queueManager,
IOptionsMonitor<WorkerConfiguration> configuration
)
{
this.Configuration = configuration.CurrentValue;
configuration.OnChange(updatedConfig =>
{
this.Configuration = updatedConfig;
});
this.queueManager = queueManager;
_httpClient = new HttpClient();
}
public async Task RouteMessages()
{
while (true)
{
//bool lecture = bool.Parse(Configuration.GetSection("WorkerConfiguration")["Lecture"]);
//int TPS = int.Parse(Configuration.GetSection("WorkerConfiguration")["TPS"]);
//string OutboundQueue = Configuration.GetSection("WorkerConfiguration")["OutboundQueue"];
if (!this.Configuration.Lecture)
{
await Task.Delay(1000);
continue;
};
var messageAmountToConsume = this.Configuration.TPS; // Start amount
var now = DateTime.UtcNow;
List<Message> messages = await this.queueManager.FetchItem<Message>(messageAmountToConsume);
this.queueManager.Publish(messages, this.Configuration.OutboundQueue);
var endDate = DateTime.UtcNow;
TimeSpan timestamp = endDate - now;
int timeGap = (int)timestamp.TotalMilliseconds;
if (1000 - timeGap > 0)
await Task.Delay(1000 - timeGap);
}
}
}
}
在这种情况下,我的代码使用IOptionsMonitor(不起作用),但在过去我也尝试过IOptionsSnapshot,但也不起作用。
我会继续关注正在发生的事情,但我非常感谢知道你对此的看法,并知道我忘记了什么。
谢谢:D