.NET 6 + Hangfire 实现后台作业管理
2023-02-18 15:41:30 时间
一.环境:
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();
运行项目:
hangfire访问地址链接,输入账号admin,密码admin
https://localhost:5001/hangfire
自动创建了数据库表:
【小结】
Hangfire是当今最流行的任务调度框架之一,大型系统中常常会用到。
相关文章
- [PHP] laravel中的api路由前缀
- [PHP] 服务容器绑定接口测试
- [mysql] join查询没有走索引的原因
- [mysql] left join 和 join 和right join的区别
- [PHP] 理解依赖注入容器-自动注入
- [PHP] 理解依赖注入容器
- [PHP] ::class的具体作用
- [PHP] composer install和composer update的区别
- [PHP] 解决composer install报错: it could not be found in any version, there may be a typo in the package name
- [PHP] 对象和引用
- [HTTP] post传递数据的两种content-type application/x-www-form-urlencoded multipart/form-data
- [Nginx]使用ngx_http_image_filter_module实现压缩图片为缩略图
- [tcp] 服务端大量close_wait 和 time_wait状态
- [nginx] nginx的变量拼接与if判断
- [nginx] nginx的常用内置变量
- [PHP] 发布一个类库到composer
- [PHP] 重要操作手机短信验证逻辑梳理
- [css] position:fixed居中问题
- [PHP] xml转对象函数simplexml_load_string
- [MySQL] 理解MySQL索引合并index_merge