feat: 支持hangfire内存模式

This commit is contained in:
橙子
2025-02-07 17:52:38 +08:00
parent 9e143c0a75
commit 373877cfcf
2 changed files with 24 additions and 4 deletions

View File

@@ -1,7 +1,10 @@
using Hangfire; using System.Linq.Expressions;
using Hangfire;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.BackgroundWorkers; using Volo.Abp.BackgroundWorkers;
using Volo.Abp.BackgroundWorkers.Hangfire; using Volo.Abp.BackgroundWorkers.Hangfire;
using Volo.Abp.DynamicProxy;
namespace Yi.Framework.BackgroundWorkers.Hangfire; namespace Yi.Framework.BackgroundWorkers.Hangfire;
@@ -19,12 +22,29 @@ public class YiFrameworkBackgroundWorkersHangfireModule : AbpModule
var backgroundWorkerManager = context.ServiceProvider.GetRequiredService<IBackgroundWorkerManager>(); var backgroundWorkerManager = context.ServiceProvider.GetRequiredService<IBackgroundWorkerManager>();
var works = context.ServiceProvider.GetServices<IHangfireBackgroundWorker>(); var works = context.ServiceProvider.GetServices<IHangfireBackgroundWorker>();
var configuration = context.ServiceProvider.GetRequiredService<IConfiguration>();
//【特殊,为了兼容内存模式,由于内存模式任务,不能使用队列】
bool.TryParse(configuration["Redis:IsEnabled"], out var redisEnabled);
foreach (var work in works) foreach (var work in works)
{ {
//如果为空默认使用服务器本地utc时间 //如果为空默认使用服务器本地utc时间
work.TimeZone ??= TimeZoneInfo.Local; work.TimeZone ??= TimeZoneInfo.Local;
if (redisEnabled)
{
await backgroundWorkerManager.AddAsync(work); await backgroundWorkerManager.AddAsync(work);
} }
else
{
object unProxyWorker = ProxyHelper.UnProxy((object)work);
RecurringJob.AddOrUpdate(work.RecurringJobId,
(Expression<Func<Task>>)(() =>
((IHangfireBackgroundWorker)unProxyWorker).DoWorkAsync(default(CancellationToken))),
work.CronExpression, new RecurringJobOptions()
{
TimeZone = work.TimeZone
});
}
}
} }
public override void OnPreApplicationInitialization(ApplicationInitializationContext context) public override void OnPreApplicationInitialization(ApplicationInitializationContext context)

View File

@@ -188,10 +188,10 @@ namespace Yi.Abp.Web
//配置Hangfire定时任务存储开启redis后优先使用redis //配置Hangfire定时任务存储开启redis后优先使用redis
var redisConfiguration = configuration["Redis:Configuration"]; var redisConfiguration = configuration["Redis:Configuration"];
var redisEnabled = configuration["Redis:IsEnabled"];
context.Services.AddHangfire(config=> context.Services.AddHangfire(config=>
{ {
if (redisEnabled.IsNullOrEmpty() || bool.Parse(redisEnabled)) bool.TryParse( configuration["Redis:IsEnabled"], out var redisEnabled);
if (redisEnabled)
{ {
config.UseRedisStorage( config.UseRedisStorage(
ConnectionMultiplexer.Connect(redisConfiguration), ConnectionMultiplexer.Connect(redisConfiguration),