.NET 6 + Hangfire 实现后台作业管理
2024-09-18 18:27:17
一.环境:
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();
运行项目:
自动创建了数据库表:
最新文章
- 关于DOM的一些笔记(一)
- gradle项目中profile的实现
- es6 ajax
- 第一次在linux上登录博客
- tamper绕WAF小结
- CSS学起来并不难
- 【python】argparse模块
- Python 读写excel数据
- angularjs--$watch、$watchGroup、$watchCollection含义
- post 提交数据
- js刷新页面
- Eclipse连接MySQL出现Server time zone is unrecognized错误
- vue入门 vue与react和Angular的关系和区别
- mysql 获取原数据
- DesignModeler&;nbsp;GestureRecgin…
- Swift 之Carthage
- VS Code直接编辑下一行
- 模拟Http请求的几种常用方式
- Java EE 课程目标
- 如何用java读取properties文件