Abp集成HangFire

簡要說明

後臺作業在系統開發的過程當中,是比較常用的功能。因爲總是有一些長耗時的任務,而這些任務我們不是立即響應的,例如 Excel 文檔導入、批量發送短信通知等。
ABP vNext 提供了後臺作業的支持,並且還提供了對 HangFire 和 RabbitMQ 的後臺作業集成。開發人員在使用這些第三方庫的時候,基本就是開箱即用,不需要做其他複雜的配置。
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();
 
           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)
       {
 
       }
   }

結尾

更多的ABP相關問題和集成,歡迎您加入我的知識星球,或者我的QQ羣:996767213。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章