安裝Hangfire
在webapi項目中通過nuget安裝Hangfire.Core,Hangfire.SqlServer,Hangfire.AspNetCore,截止到目前的最新版本是1.7.6。
使用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(); }
啟動項目
可以看到數據庫中自動創建了幾張表。
在項目地址后面加上/hangfire進入hangfire任務面板,這個面板可以說和CAP的面板一摸一樣了😁