天天看點

.NET Core Hangfire任務計劃

安裝Hangfire

 建立ASP.NET Core空 項目,.Net Core版本3.1

.NET Core Hangfire任務計劃

 往*.csproj添加包引用,添加新的PackageReference标記。如下所示。請注意,下面代碼段中的版本可能已經過時,如有需要,請使用nuget擷取最新版本。

<ItemGroup>
  <PackageReference Include="Hangfire.Core" Version="1.7.28" />
  <PackageReference Include="Hangfire.SqlServer" Version="1.7.28" />
  <PackageReference Include="Hangfire.AspNetCore" Version="1.7.28" />
</ItemGroup>      

建立資料庫

從上面的代碼片段中可以看到,在本文中,我們将使用SQL Server作為作業存儲。在配置Hangfire之前,您需要為它建立一個資料庫,或者使用現有的資料庫。下面的配置字元串指向本地計算機上SQLEXPRESS執行個體中的HangfireTest資料庫。

您可以使用SQLServerManagementStudio或任何其他方式執行以下SQL指令。如果您使用的是其他資料庫名稱或執行個體,請確定在接下來的步驟中配置Hangfire時更改了連接配接字元串。

CREATE DATABASE [HangfireTest]
GO      

配置Settings

下面将定義HangfireConnection連接配接來進行表遷移,同時AspNetCore與Hangfire進行了日志記錄內建。Hangfire的日志資訊有時非常重要,有助于診斷不同的問題。資訊級别允許檢視Hangfire的工作情況,警告和更高的日志級别有助于調查問題,建議調整日志級别

{
  "ConnectionStrings": {
    "HangfireConnection": "Server=.\\sqlexpress;Database=HangfireTest;Integrated Security=SSPI;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Hangfire": "Information"
    }
  }
}      

更新應用程式設定後,打開Startup.cs檔案。startup類是.NET CORE應用程式的配置。首先,我們需要導入Hangfire名稱空間,由于建的是空項目,是以還需要導入Configuration.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Hangfire;
using Hangfire.SqlServer;      

注冊服務

   使用asp.netcore内置DI注入Hangfire服務

public Startup(IConfiguration configuration)

  {

     Configuration = configuration;

  }

  public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    // Add Hangfire services.
    services.AddHangfire(configuration => configuration
        .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
        .UseSimpleAssemblyNameTypeSerializer()
        .UseRecommendedSerializerSettings()
        .UseSqlServerStorage(Configuration.GetConnectionString("HangfireConnection"), new SqlServerStorageOptions
        {
            CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
            SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
            QueuePollInterval = TimeSpan.Zero,
            UseRecommendedIsolationLevel = true,
            DisableGlobalLocks = true
        }));

    // Add the processing server as IHostedService
    services.AddHangfireServer();
}      

添加Hangfire面闆

   如果隻是作為背景作業,也可不使用面闆功能,按需添加

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
     app.UseRouting();
     app.UseEndpoints(endpoints =>
     {      

         endpoints.MapGet("/", async context =>

         {

            await context.Response.WriteAsync("Hello World!");

         });

          endpoints.MapHangfireDashboard();

});
      
BackgroundJob.Enqueue(() => Console.WriteLine("測試"));      
}      

運作程式

 生成資料表

.NET Core Hangfire任務計劃

  通路http://localhost:5000/hangfire

.NET Core Hangfire任務計劃

添加Hangfire面闆授權

建立MyAuthorizationFilter.cs

public class MyAuthorizationFilter : IDashboardAuthorizationFilter
    {
        public bool Authorize(DashboardContext context)
        {
            var httpContext = context.GetHttpContext();
            string header = httpContext.Request.Headers["Authorization"];//擷取授權
            if(header == null)
                return AuthenicateLogin();
            //解析授權
            var authHeader = AuthenticationHeaderValue.Parse(header);
            var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
            var credentials = Encoding.UTF8.GetString(credentialBytes).Split(new[] { ':' }, 2);
            var username = credentials[0];
            var password = credentials[1];
            //驗證登入
            if (username == "admin" && password =="123456")
                return true;
            else
                return AuthenicateLogin();
            //跳轉簡單登入界面
            bool AuthenicateLogin()
            {
                httpContext.Response.StatusCode = 401;
                httpContext.Response.Headers.Append("WWW-Authenticate", "Basic realm=\"Hangfire Dashboard\"");
                context.Response.WriteAsync("Authenticatoin is required.");
                return false;
            }
            
        }
    }      

Hangfire面闆修改

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {      

                 endpoints.MapHangfireDashboard(new DashboardOptions

                 {

                    Authorization = new[] { new MyAuthorizationFilter() }

                 });

endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });

            BackgroundJob.Enqueue(() => Console.WriteLine("測試"));
   }      

運作程式

.NET Core Hangfire任務計劃
.NET Core Hangfire任務計劃

 文檔連結:https://docs.hangfire.io/en/latest/getting-started/index.html