天天看點

在.netcore webapi項目中使用背景任務工具Hangfire

安裝Hangfire

  在webapi項目中通過nuget安裝Hangfire.Core,Hangfire.SqlServer,Hangfire.AspNetCore,截止到目前的最新版本是1.7.6。

在.netcore webapi項目中使用背景任務工具Hangfire

使用MSSQL資料庫

  可以建立一個新的資料庫,或者使用現有資料庫。

CREATE DATABASE [HangfireTest]
GO      

 設定appsettings.json

{
  "ConnectionStrings": {
    "Hangfire": "Server=.;Database=mssqllocaldb;Integrated Security=SSPI;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Hangfire": "Information"
    }
  },
  "AllowedHosts": "*"
}      

注冊hangfire服務

  在startup.cs引用Hangfire和Hangfire.SqlServer,然後注冊hangfire服務。

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // 注冊Hangfire服務
    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,
            UsePageLocksOnDequeue = true,
            DisableGlobalLocks = true
        }));

    services.AddHangfireServer();

    services.AddMvc();
}      

  修改configure方法

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IBackgroundJobClient backgroundJobs, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHangfireDashboard();
    backgroundJobs.Enqueue(() => Console.WriteLine("hello from hangfire"));

    app.UseHttpsRedirection();
    app.UseMvc();
}      

啟動項目

  可以看到資料庫中自動建立了幾張表。

在.netcore webapi項目中使用背景任務工具Hangfire

  在項目位址後面加上/hangfire進入hangfire任務面闆,這個面闆可以說和CAP的面闆一摸一樣了😁

在.netcore webapi項目中使用背景任務工具Hangfire
在.netcore webapi項目中使用背景任務工具Hangfire