一.环境:
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连接:
代码语言:javascript复制"ConnectionStrings": {
"HangfireConnection": "server=192.168.5.234;Database=hangfiredb;userid=root;password=123456;SslMode=none;Allow User Variables=true;"
},
Programe.cs程序:
代码语言:javascript复制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();
运行项目:
hangfire访问地址链接,输入账号admin,密码admin
https://localhost:5001/hangfire
自动创建了数据库表:
【小结】
Hangfire是当今最流行的任务调度框架之一,大型系统中常常会用到。