asp.net core接入hangfire

在开始我们的教程之前,我们需要有一个工作的ASP.NET Core应用程序。本文档专门介绍Hangfire,请阅读官方ASP.NET Core文档,了解如何创建和初始化新的web应用程序。

安装Hangfire

Hangfire是一组NuGet包,因此您需要通过添加新的PackageReference标记将它们添加到*.csproj文件中,如下所示。请注意,下面代码段中的版本可能已过时,因此请使用以下徽章中的版本。它们会实时更新。

<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.App" />
  <PackageReference Include="Hangfire.Core" Version="1.7.*" />
  <PackageReference Include="Hangfire.SqlServer" Version="1.7.*" />
  <PackageReference Include="Hangfire.AspNetCore" Version="1.7.*" />
</ItemGroup>

也可以使用内存存储
在这里插入图片描述

创建数据库

如果使用内存存储则跳过
从上面的代码片段中可以看到,在本文中,我们将使用SQL Server作为作业存储。在配置Hangfire之前,您需要为其创建一个数据库,或使用现有数据库。下面的配置字符串指向本地计算机上SQLEXPRESS实例中的HangfireTest数据库。
可以使用SQLServerManagementStudio或任何其他方式执行以下SQL命令。如果您正在使用其他数据库名称或实例,请确保在接下来的步骤中配置Hangfire时更改了连接字符串。

CREATE DATABASE [HangfireTest]
GO

配置Hangfire

我们将从定义Hangfire.SqlServer包的配置字符串开始配置过程。假设您在本地主机上运行了一个名为sqlexpress的实例,并且刚刚创建了“HangfireTest”数据库。当前用户应该能够创建表,以允许自动迁移来完成其工作。
此外,Hangfire.AspNetCore包还与ASP.NET Core应用程序进行了日志记录集成。Hangfire的日志信息有时非常重要,有助于诊断不同的问题。信息级别允许查看Hangfire的工作情况,警告和更高的日志级别有助于调查问题。

配置设置

打开appsettings.json文件,并从以下代码段中添加高亮显示的行。

{
  "ConnectionStrings": {
    "HangfireConnection": "Server=.\\sqlexpress;Database=HangfireTest;Integrated Security=SSPI;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Hangfire": "Information"
    }
  }
}

更新应用程序设置后,打开Startup.cs文件。启动类是ASP.NET核心应用程序配置的核心。首先,我们需要导入Hangfire命名空间。

// ...
using Microsoft.Extensions.DependencyInjection;
using Hangfire;
using Hangfire.SqlServer;

注册服务

依赖注入是ASP.NET核心中引入的主要技术之一。Hangfire.AspNetCore集成包添加了一个扩展方法来注册所有服务、它们的实现以及日志记录和作业激活器。作为一个参数,它采取一个允许配置Hangfire本身的操作。

以下配置设置仅适用于新安装。其中一些设置可能与现有安装不兼容,升级到更新版本时,请参阅升级指南。

public void ConfigureServices(IServiceCollection services)
{
    // Add Hangfire services.
    services.AddHangfire(configuration => configuration
        .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
        .UseSimpleAssemblyNameTypeSerializer()
        .UseRecommendedSerializerSettings()
        .UseSqlServerStorage(Configuration.GetConnectionString("HangfireConnection"), new SqlServerStorageOptions
        {
            CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
            SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
            QueuePollInterval = TimeSpan.Zero,
            UseRecommendedIsolationLevel = true,
            DisableGlobalLocks = true
        }));
/*
使用内存存储
services.AddHangfire(x => x.UseStorage(new MemoryStorage()));
services.AddHangfireServer();
*/
    // Add the processing server as IHostedService
    services.AddHangfireServer();

    // Add framework services.
    services.AddMvc();
}

添加仪表板UI

注册Hangfire类型后,您现在可以选择需要添加到应用程序中的功能。下面的代码片段向您展示了如何添加Dashboard UI以立即使用所有Hangfire功能。以下行是完全可选的,如果您的应用程序只创建后台作业,您可以完全删除它们,因为单独的应用程序将处理它们。

非本地请求需要授权配置。默认情况下,仅允许本地访问Hangfire Dashboard。必须配置仪表板授权才能允许远程访问。

public void Configure(IApplicationBuilder app, IBackgroundJobClient backgroundJobs, IHostingEnvironment env)
{
    // ...
    app.UseStaticFiles();

    app.UseHangfireDashboard();
    backgroundJobs.Enqueue(() => Console.WriteLine("Hello world from Hangfire!"));

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

从Hangfire.AspNetCore 1.7.8开始,Hangfire正式支持ASP.NET Core 3.0端点路由。在MapHangfireDashboard中使用RequireAuthorization时,请注意默认情况下只允许本地访问。

 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
     app.UseRouting();
     app.UseAuthorization();
     app.UseEndpoints(endpoints =>
     {
         endpoints.MapControllers();
         endpoints.MapHangfireDashboard();
     });
 }

启动应用程序

运行以下命令启动应用程序,或在Visual Studio中单击F5按钮。

dotnet run

启动应用程序并成功启动后台处理后,应显示以下消息。

info: Hangfire.SqlServer.SqlServerStorage[0]
    Start installing Hangfire SQL objects...
    Hangfire SQL objects installed.
    Using job storage: 'SQL Server: .\@AspNetCoreTest'
    Using the following options for SQL Server job storage:
        Queue poll interval: 00:00:15.
info: Hangfire.BackgroundJobServer[0]
    Starting Hangfire Server...
    Using the following options for Hangfire Server:
        Worker count: 20
        Listening queues: 'default'
        Shutdown timeout: 00:00:15
        Schedule polling interval: 00:00:15

这些行包含有关用于持久化后台作业的SQL Server作业存储以及正在处理所有后台作业的后台作业服务器的消息。
由于我们创建了后台作业,因此还应该显示以下消息,该作业的唯一行为是向控制台写入消息。

Hello world from Hangfire!

应用程序启动后,打开以下URL(假设您的应用程序在5000端口上运行),以访问Hangfire Dashboard界面。正如我们所看到的,我们的后台工作成功完成了。
http://localhost:5000/hangfire
在这里插入图片描述
使用完应用程序后,按控制台窗口中的Ctrl+C停止应用程序。出现以下消息,告诉您后台处理服务器已正常停止。

info: Hangfire.BackgroundJobServer[0]
   Hangfire Server stopped.

您也可以终止进程,但在这种情况下,某些后台作业可能会在调用时延迟。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值