.NET 6 + Hangfire 实现后台作业管理
一.环境:
ASP.NET Core 6 + Hangfire + MySQL
二、新建ASP.NET Core空项目
项目名称:HangfireExample
框架:.NET 6.0
三、Nuget引入程序集
Hangfire.Core
Hangfire.MySqlStorage --mysql数据库存储
Hangfire.AspNetCore --AspNetCore支持
Hangfire.Dashboard.BasicAuthorization --可视化+权限控制
Hangfire.HttpJob --httpJob
创建MySQL数据库:hangfiredb
appsettings.json配置MySQL连接:
"ConnectionStrings": { "HangfireConnection": "server=192.168.5.234;Database=hangfiredb;userid=root;password=123456;SslMode=none;Allow User Variables=true;" },
Programe.cs程序:
using Hangfire; using Hangfire.Dashboard.BasicAuthorization; using Hangfire.HttpJob; using Hangfire.MySql; using System.Configuration; using System.Transactions; using static System.Net.WebRequestMethods; var builder = WebApplication.CreateBuilder(args); var Config = builder.Configuration; // Add Hangfire services. builder.Services.AddHangfire(configuration => configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseStorage(new MySqlStorage( Config["ConnectionStrings:HangfireConnection"], new MySqlStorageOptions { TransactionIsolationLevel = IsolationLevel.ReadCommitted, QueuePollInterval = TimeSpan.FromSeconds(15), JobExpirationCheckInterval = TimeSpan.FromHours(1), CountersAggregateInterval = TimeSpan.FromMinutes(5), PrepareSchemaIfNecessary = true, DashboardJobListLimit = 50000, TransactionTimeout = TimeSpan.FromMinutes(1), TablesPrefix = "Hangfire" })).UseHangfireHttpJob()); // Add the processing server as IHostedService builder.Services.AddHangfireServer(); var app = builder.Build(); app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new[] {new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions { RequireSsl = false, SslRedirect = false, LoginCaseSensitive = true, Users = new [] { new BasicAuthAuthorizationUser { Login = "admin", PasswordClear = "admin" } } })} }); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); }); }); //app.MapGet("/", () => "Hello World!"); app.Run();
运行项目:
自动创建了数据库表: