ASP.NET Core 8.0 中使用 Hangfire 调度 API

        在这篇博文中,我们将引导您完成将 Hangfire 集成到 ASP.NET Core NET Core 项目中以安排 API 每天运行的步骤。Hangfire 是一个功能强大的库,可简化 .NET 应用程序中的后台作业处理,使其成为调度任务的绝佳选择。继续阅读以了解如何设置 Hangfire 并将其配置为每天运行您的 API。

为什么在 ASP.NET Core 中使用 Hangfire 执行后台作业?

在深入实现之前,让我们先了解一下为什么 Hangfire 是后台作业的首选:

    ·易于使用: Hangfire 设置和使用简单,让您专注于应用程序的核心功能。

    ·可扩展性:它可以处理大量作业,并且可扩展以满足您的应用程序的需求。

    ·可靠性: Hangfire 确保即使在服务器重启后仍能执行作业,为关键任务提供可靠性。

    ·仪表板:它带有一个用于监控作业的内置仪表板,可以轻松跟踪和管理后台进程。

Hangfire 提供的调度类型

Hangfire 支持各种类型的后台作业,使其能够灵活地应用于不同的场景。以下是它提供的主要调度类型:

    ·即发即弃作业:这些作业仅执行一次,且几乎在创建后立即执行。它们适用于需要快速完成且无需重复的任务。
    
        BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget job executed!"));
    
    ·延迟作业:这些作业仅执行一次,但不会立即执行。它们被安排在指定的延迟后运行。
    
        BackgroundJob.Schedule(() => Console.WriteLine("Delayed job executed!"), TimeSpan.FromDays(1));
    
    ·重复作业:这些作业会按照指定的 CRON 计划执行多次。它们对于需要定期运行的任务非常有用。
    
        RecurringJob.AddOrUpdate(() => Console.WriteLine("Recurring job executed!"), Cron.Daily);
    
    ·延续:这些作业在其父作业完成后执行。它们对于作业依赖于另一作业的成功完成的工作流很有用。
    
        var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("Parent job executed!"));
        BackgroundJob.ContinueWith(jobId, () => Console.WriteLine("Continuation job executed!"));

先决条件
开始之前,请确保您已准备好以下物品:

· Visual Studio 2019 或更高版本
· .NET Core SDK 安装
· ASP.NET Core 基础知识 NET Core

集成 Hangfire 的分步指南

    步骤 1:创建一个新的 ASP.NET Core Web API 项目

    首先,创建一个新的 ASP.NET Core 项目或打开一个现有项目。如果您没有任何项目,请按照此处提到的步骤创建一个。我还添加了创建测试 API 的步骤。

    第 2 步:安装 Hangfire NuGet 包

    · 转到工具>NuGet 包管理器>管理解决方案的 NuGet 包…

    · 搜索 Hangfire 并安装最新版本。

    · 搜索System.Data.SqlClient并安装最新的。 

步骤 3:创建用于 Hangfire 的数据库
打开 SSMS 并创建一个新数据库。您也可以使用现有的数据库。 

步骤 4:将连接字符串添加到 appsettings.json
在 appsettings.json 文件中,添加 SQL Server 的连接字符串: 

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"TestDatabase": "Server=SHEKHAR\\SQLEXPRESS;Database=HangfireDemo;TrustServerCertificate=True;User Id=adminuser;Password=adminuser;"
}

步骤 5:在 Program.cs 中配置 Hangfire
修改 Program.cs 文件来配置 Hangfire: 

using Hangfire;
using Hangfire.SqlServer;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Step 1 -> Hangfire configuration with SQL Server storage

var connectionString = builder.Configuration.GetConnectionString("TestDatabase");
builder.Services.AddHangfire(config =>
{
config.UseSqlServerStorage(connectionString, new SqlServerStorageOptions
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
DisableGlobalLocks = true
});
});
// Step 2 -> Add Hangfire's server.
builder.Services.AddHangfireServer();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
//Step 3 -> Added the dashboard url
app.UseHangfireDashboard("/hangfire");
app.Run(); 

步骤 6:创建后台作业来调用 API
创建一个调用 API 的后台作业。在此示例中,我使用我的 API 端点 https ://localhost:7282/api/TestApi。我们需要创建一个服务来调用此端点,然后使用 Hangfire 对其进行调度。
创建一个新的服务类 ApiCallService.cs 并添加以下代码:

namespace TestApi
{
    public class ApiCallService
    {
        private readonly HttpClient _httpClient;
        public ApiCallService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }
        public async Task CallApiEndpointAsync()
        {
            var response = await _httpClient.GetAsync("https://localhost:7282/api/TestApi");
            response.EnsureSuccessStatusCode();
            // Log success or handle the response as needed
        }
    }
}

在 Program.cs 中注册 HttpClient 和 ApiCallService:

builder.Services.AddHttpClient<ApiCallService>();

在 Program.cs 中安排作业:
// Schedule the job to call the API endpoint
RecurringJob.AddOrUpdate<ApiCallService>("call-api-endpoint", service => service.CallApiEndpointAsync(), Cron.Daily); // Adjust the schedule as needed

最终的 Program.cs 代码:

using Hangfire;
using Hangfire.SqlServer;
using TestApi;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Step 1 -> Hangfire configuration with SQL Server storage
var connectionString = builder.Configuration.GetConnectionString("TestDatabase"); 
builder.Services.AddHangfire(config =>
{
    config.UseSqlServerStorage(connectionString, new SqlServerStorageOptions
    {
        CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
        SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
        QueuePollInterval = TimeSpan.Zero,
        UseRecommendedIsolationLevel = true,
        DisableGlobalLocks = true
    });
});
// Step 2 -> Add Hangfire's server.
builder.Services.AddHangfireServer();
// Register httpclient
builder.Services.AddHttpClient<ApiCallService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
//Step 3 -> Added the dashboard url
app.UseHangfireDashboard("/hangfire");
// Schedule the job to call the API endpoint
RecurringJob.AddOrUpdate<ApiCallService>("call-api-endpoint", service => service.CallApiEndpointAsync(), Cron.Daily); // Adjust the schedule as needed
app.Run();

步骤 7:运行并监控您的应用程序
运行项目后,您将看到数据库中创建了一些新表。Hangfire 创建这些表是为了跟踪作业并执行其他操作:

访问https://localhost:7282/hangfire/上的 Hangfire 仪表板来监控您的后台作业。 

单击“重复作业”选项卡可查看所有重复作业。目前仅显示我们已安排的作业。 

单击“作业”>“成功”以查看作业的状态。 

要获取更多详细信息,请单击该职位: 

最终代码:
这是已添加所有的代码:https://download.youkuaiyun.com/download/hefeng_aspnet/89918351

结论
        通过遵循本指南,您已将 Hangfire 集成到您的 . NET 8 项目中,并使用 SQL Server 作为存储提供程序,安排了使用 Hangfire 的 API 调用。此设置可确保您的 API 按照指定的时间表定期调用。有关更多高级 Hangfire 配置和存储选项,请参阅官方 Hangfire 文档

<think>好的,我需要帮助用户了解如何在.NET 8.0 WebAPI中配置Hangfire。首先,我需要回忆Hangfire的基本概念和它在.NET项目中的作用。Hangfire是一个用于处理后台任务的开源库,支持定时任务、延迟任务和队列任务,适用于需要在后台执行长时间运行的操作的场景。 接下来,我得考虑在.NET 8.0 WebAPI项目中配置Hangfire的具体步骤。首先,用户需要安装相关的NuGet包。Hangfire的核心包包括Hangfire.CoreHangfire.AspNetCore,以及用于存储的Hangfire.SqlServer,如果使用SQL Server作为存储的话。所以第一步应该是通过NuGet安装这些包。 安装完成后,下一步是在Program.cs文件中配置Hangfire服务。这里需要添加Hangfire的服务到依赖注入容器中,通常使用AddHangfire方法,并配置连接字符串指向SQL Server数据库。同时,可能还需要配置Hangfire的Dashboard,以便通过网页界面监控任务状态。这需要调用UseHangfireDashboard方法,并注意权限控制,避免未授权访问。 然后,用户需要初始化Hangfire的存储,确保数据库表已经创建。Hangfire使用SQL Server时会自动创建必要的表,但需要确认连接字符串正确无误,并且数据库有足够的权限。 接下来是使用Hangfire的示例部分。可能需要演示如何创建后台任务、延迟任务和定时任务。比如,使用BackgroundJob.Enqueue方法执行即时任务,BackgroundJob.Schedule执行延迟任务,以及RecurringJob.AddOrUpdate设置定时任务。这些示例需要确保代码正确,并且参数如Cron表达式是有效的。 此外,需要注意的细节包括:在开发环境和生产环境中Dashboard的访问权限控制,可能通过环境判断来限制访问;Hangfire服务需要在应用启动时正确配置,避免因配置错误导致任务无法执行;以及确保数据库连接稳定,避免存储问题导致任务丢失。 用户可能还会遇到常见问题,比如Dashboard无法访问,这时候需要检查中间件的顺序是否正确,或者权限设置是否过于严格。另外,任务没有执行可能需要检查Hangfire的服务是否正常启动,或者存储配置是否正确。 最后,总结整个配置过程,强调关键步骤和注意事项,帮助用户巩固理解。可能需要提醒用户在实际项目中根据需求调整配置,例如使用不同的存储方式,或者更复杂的权限控制策略。</think>在.NET 8.0 WebAPI中配置Hangfire可分为以下步骤: --- ### **1. 安装NuGet包** 通过NuGet安装以下核心依赖: ```bash Install-Package Hangfire.AspNetCore Install-Package Hangfire.SqlServer # 如果使用SQL Server作为存储 ``` --- ### **2. 配置服务与中间件** 在`Program.cs`中添加Hangfire服务: ```csharp var builder = WebApplication.CreateBuilder(args); // 添加Hangfire服务 builder.Services.AddHangfire(config => { config.UseSqlServerStorage(builder.Configuration.GetConnectionString("HangfireConnection")); }); builder.Services.AddHangfireServer(); // 启用后台任务处理服务器 ``` --- ### **3. 初始化数据库存储** 若使用SQL Server,需确保: - 配置文件中包含连接字符串: ```json "ConnectionStrings": { "HangfireConnection": "Server=.;Database=HangfireTest;Integrated Security=SSPI;" } ``` - 首次运行时,Hangfire会自动创建所需表。 --- ### **4. 启用Hangfire Dashboard** 在`Program.cs`中添加中间件: ```csharp var app = builder.Build(); // 配置Dashboard(建议限制访问权限) app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new[] { new HangfireAuthorizationFilter() } }); ``` --- ### **5. 创建任务授权过滤器(可选)** 防止未授权访问Dashboard: ```csharp public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter { public bool Authorize(DashboardContext context) { // 示例:仅允许本地环境访问 var httpContext = context.GetHttpContext(); return httpContext.Request.IsLocal(); } } ``` --- ### **6. 编写任务示例** 在控制器或服务中调用: ```csharp // 即时任务 BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget任务执行!")); // 延迟任务(5分钟后执行) BackgroundJob.Schedule(() => Console.WriteLine("延迟任务执行!"), TimeSpan.FromMinutes(5)); // 定时任务(每分钟执行) RecurringJob.AddOrUpdate("my-recurring-job", () => Console.WriteLine("定时任务执行!"), Cron.Minutely); ``` --- ### **7. 运行与验证** 1. 启动WebAPI项目。 2. 访问`https://localhost:{port}/hangfire`打开Dashboard。 3. 查看任务执行状态及日志。 --- ### **注意事项** 1. **存储选择**:除SQL Server外,Hangfire支持Redis、PostgreSQL等。 2. **生产环境安全**:务必限制Dashboard的访问权限。 3. **依赖注入**:任务方法需为`public`,且依赖项需通过DI容器注入。 4. **异常处理**:通过`GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 3 })`配置自动重试。 --- ### **扩展场景** - **集成MediatR**:将Hangfire与MediatR结合,处理复杂后台逻辑。 - **分布式部署**:多节点部署时需配置相同的存储数据库。 - **性能监控**:通过Dashboard分析任务执行时间及失败率。 如需进一步优化,可参考[Hangfire官方文档](https://www.hangfire.io/)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

csdn_aspnet

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值