Loading

.NET Core 6使用Hangfire 实现后台作业管理

一、环境参数

IDE环境 :Visual Studio 2022

框架环境:ASP.NET Core 6 + Hangfire + MySQL

 

二、新建ASP.NET Core空项目

 

  

 

三、Nuget引入程序集

Hangfire 作为几个 NuGet 包分发,从主要包 Hangfire.Core 开始,它包含所有主要类和抽象。
Hangfire.SqlServer 等其他包提供功能或抽象实现。
要开始使用 Hangfire,请安装主软件包并选择一个可用的存储。

这里我是用MySql作为Hangfire的Storage。Hangfire 官方在免费版中只提供了 SqlServer 接入的支持,在收费版多一个 Redis。
需要 MongoDB、SqlServer 、PostgreSql、SQLite 等其他 Storages 的可以自己寻找第三方的开源项目,
这里有一个官方推荐的扩展清单https://www.hangfire.io/extensions.html,清单中列出了一些其他种类的 Storages。

 

 

1、添加Nuget引入程序集

Hangfire.Core
Hangfire.MySqlStorage                   --mysql数据库存储
Hangfire.AspNetCore                     --AspNetCore支持
Hangfire.Dashboard.BasicAuthorization   --可视化+权限控制
Hangfire.HttpJob                        --httpJob

  

2、先创建MySQL数据库

hangfiredb

  

3、直接贴代码Program.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.Run();

  

可选参数说明:

TransactionIsolationLevel- 事务隔离级别。默认为已提交读。
QueuePollInterval- 作业队列轮询间隔。默认值为 15 秒。
JobExpirationCheckInterval- 作业过期检查间隔(管理过期记录)。默认值为 1 小时。
CountersAggregateInterval- 聚合计数器的间隔。默认为 5 分钟。
PrepareSchemaIfNecessary- 如果设置为true,它会创建数据库表。默认为true。
DashboardJobListLimit- 仪表板作业列表限制。默认值为 50000。
TransactionTimeout- 交易超时。默认值为 1 分钟。
TablesPrefix- 数据库中表的前缀。默认为无

  

4、appsettings.json设置MySQL路径

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.Hosting.Lifetime": "Information",
      "Hangfire": "Information"
    }
  },
  "ConnectionStrings": {
    "HangfireConnection": "server=x.x.x.x;Database=hangfiredb;userid=root;password=123456;SslMode=none;Allow User Variables=true;"
  },
  "AllowedHosts": "*"
}

  

四、运行项目

1、项目已经跑起来了

 

2、访问地址链接,输入账号admin,密码admin

https://localhost:7223/hangfire

 

 

更详细的介绍链接

https://blog.csdn.net/liyou123456789/article/details/125449302

 

posted @ 2022-10-03 00:37  梦想PHOTO  阅读(961)  评论(0编辑  收藏  举报