概述
ABP vNext 提供了后台工作者和后台作业的支持,基本实现与原来的 ABP 框架类似,并且 ABP vNext 还提供了对 HangFire 和 RabbitMQ 的后台作业集成。开发人员在使用这些第三方库的时候,基本就是开箱即用,不需要做其他复杂的配置。
后台作业在系统开发的过程当中,是比较常用的功能。因为总是有一些长耗时的任务,而这些任务我们不是立即响应的,例如 Excel 文档导入、批量发送短信通知等。
后台工作者 的话,ABP vNext 的实现就是在 CLR 的 Timer 之上封装了一层,周期性地执行用户逻辑。ABP vNext 默认提供的 后台任务管理器,就是在后台工作者基础之上进行的封装。
涉及到后台任务、后台工作者的模块一共有 6 个,它们分别是:
Volo.Abp.Threading :提供了一些常用的线程组件,其中 AbpTimer 就是在里面实现的。
Volo.Abp.BackgroundWorkers :后台工作者的定义和实现。
Volo.Abp.BackgroundJobs.Abstractions :后台任务的一些共有定义。
Volo.Abp.BackgroundJobs :默认的后台任务管理器实现。
Volo.Abp.BackgroundJobs.HangFire :基于 Hangfire 库实现的后台任务管理器。
Volo.Abp.BackgroundJobs.RabbitMQ :基于 RabbitMQ 实现的后台任务管理器。
什么是HangFire
Hangfire 是一个开源的.NET任务调度框架,目前1.6+版本已支持.NET Core。个人认为它最大特点在于内置提供集成化的控制台,方便后台查看及监控
代码实现
引用
<PackageReference Include="Volo.Abp.AspNetCore.Mvc" Version="1.0.2" /><PackageReference Include="Volo.Abp.Autofac" Version="1.0.2" /><PackageReference Include="Hangfire" Version="1.7.7" /><PackageReference Include="Hangfire.AspNetCore" Version="1.7.7" /><PackageReference Include="Hangfire.Dashboard.BasicAuthorization" Version="1.0.2" /><PackageReference Include="Hangfire.Redis.StackExchange.StrongName" Version="1.7.0" />
启动
public class Startup{public void ConfigureServices(IServiceCollection services){services.AddApplication<AppModule>();var Configuration = services.GetConfiguration();GlobalStateHandlers.Handlers.Add(new SucceededStateExpireHandler(int.Parse(Configuration["Hangfire:JobExpirationTimeout"])));services.AddHostedService<RecurringJobsService>();services.AddHangfire(x =>{var connectionString = Configuration["Hangfire:Redis:ConnectionString"];x.UseRedisStorage(connectionString, new RedisStorageOptions(){//活动服务器超时时间InvisibilityTimeout = TimeSpan.FromMinutes(60),Db = int.Parse(Configuration["Hangfire:Redis:Db"])});x.UseDashboardMetric(DashboardMetrics.ServerCount).UseDashboardMetric(DashboardMetrics.RecurringJobCount).UseDashboardMetric(DashboardMetrics.RetriesCount).UseDashboardMetric(DashboardMetrics.AwaitingCount).UseDashboardMetric(DashboardMetrics.EnqueuedAndQueueCount).UseDashboardMetric(DashboardMetrics.ScheduledCount).UseDashboardMetric(DashboardMetrics.ProcessingCount).UseDashboardMetric(DashboardMetrics.SucceededCount).UseDashboardMetric(DashboardMetrics.FailedCount).UseDashboardMetric(DashboardMetrics.EnqueuedCountOrNull).UseDashboardMetric(DashboardMetrics.FailedCountOrNull).UseDashboardMetric(DashboardMetrics.DeletedCount);});}public void Configure(IApplicationBuilder app, IConfiguration Configuration){app.InitializeApplication();app.UseAuthorization();var filter = new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions{SslRedirect = false,RequireSsl = false,LoginCaseSensitive = false,Users = new[]{new BasicAuthAuthorizationUser{Login = Configuration["Hangfire:Login"] ,PasswordClear= Configuration["Hangfire:PasswordClear"]}}});app.UseHangfireDashboard("", new DashboardOptions{Authorization = new[]{filter},});var jobOptions = new BackgroundJobServerOptions{Queues = new[] { "critical", "test", "default" },WorkerCount = Environment.ProcessorCount * int.Parse(Configuration["Hangfire:ProcessorCount"]),ServerName = Configuration["Hangfire:ServerName"],SchedulePollingInterval = TimeSpan.FromSeconds(1), //计划轮询间隔 支持任务到秒};app.UseHangfireServer(jobOptions);}}
设置
/// <summary>/// 已完成的job设置过期,防止数据无限增长/// </summary>public class SucceededStateExpireHandler : IStateHandler{public TimeSpan JobExpirationTimeout;public SucceededStateExpireHandler(int jobExpirationTimeout){JobExpirationTimeout = TimeSpan.FromMinutes(jobExpirationTimeout);}public string StateName => SucceededState.StateName;public void Apply(ApplyStateContext context, IWriteOnlyTransaction transaction){context.JobExpirationTimeout = JobExpirationTimeout;}public void Unapply(ApplyStateContext context, IWriteOnlyTransaction transaction){}}
源码下载
https://github.com/conanl5566/dotnet-core-Example/tree/master/WebApplication15%20-%20%E5%89%AF%E6%9C%AC