亲宝软件园·资讯

展开

Abp集成HangFire框架

张飞洪 人气:0

简要说明

后台作业在系统开发的过程当中,是比较常用的功能。因为总是有一些长耗时的任务,而这些任务我们不是立即响应的,例如 Excel 文档导入、批量发送短信通知等。

ABP vNext 提供了后台作业的支持,并且还提供了对 HangFire 和 RabbitMQ 的后台作业集成。开发人员在使用这些第三方库的时候,基本就是开箱即用,不需要做其他复杂的配置。

ABP vNext 的实现就是在 CLR 的 Timer 之上封装了一层,周期性地执行用户逻辑。
ABP vNext 默认提供的 后台任务管理器,就是在后台作业基础之上进行的封装。

涉及到后台任务的模块一共有 6 个,它们分别是:

什么是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();
           var Configuration = services.GetConfiguration();
           GlobalStateHandlers.Handlers.Add(new SucceededStateExpireHandler(int.Parse(Configuration["Hangfire:JobExpirationTimeout"])));
           services.AddHostedService();
           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);
       }
   }

设置

///
   /// 已完成的job设置过期,防止数据无限增长
   ///
   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)
       {
       }
   }

加载全部内容

相关教程
猜你喜欢
用户评论