其他分享
首页 > 其他分享> > .NetCore Hangfire任务计划

.NetCore Hangfire任务计划

作者:互联网

安装Hangfire

 新建ASP.NET Core空 项目,.Net Core版本3.1

 往*.csproj添加包引用,添加新的PackageReference标记。如下所示。请注意,下面代码段中的版本可能已经过时,如有需要,请使用nuget获取最新版本。

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

创建数据库

从上面的代码片段中可以看到,在本文中,我们将使用SQL Server作为作业存储。在配置Hangfire之前,您需要为它创建一个数据库,或者使用现有的数据库。下面的配置字符串指向本地计算机上SQLEXPRESS实例中的HangfireTest数据库。

 

您可以使用SQLServerManagementStudio或任何其他方式执行以下SQL命令。如果您使用的是其他数据库名称或实例,请确保在接下来的步骤中配置Hangfire时更改了连接字符串。

CREATE DATABASE [HangfireTest]
GO

配置Settings

下面将定义HangfireConnection连接来进行表迁移,同时AspNetCore包与ASP进行了日志记录集成.NET核心应用程序。Hangfire的日志信息有时非常重要,有助于诊断不同的问题。信息级别允许查看Hangfire的工作情况,警告和更高的日志级别有助于调查问题,建议调整日志级别

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

更新应用程序设置后,打开Startup.cs文件。startup类是ASP的核心。NET核心应用程序的配置。首先,我们需要导入Hangfire名称空间,由于建的是空项目,所以需要导入Configuration

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

注册服务

   使用asp.netcore内置DI注入Hangfire服务


  public Startup(IConfiguration configuration)
  {
     Configuration = configuration;
  }


  public IConfiguration Configuration { get; }


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 })); // Add the processing server as IHostedService services.AddHangfireServer(); }

添加Hangfire面板

   如果只是作为后台作业,也可不使用面板功能,按需添加

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
     app.UseRouting();
     app.UseEndpoints(endpoints =>
     {

         endpoints.MapGet("/", async context =>
         {
            await context.Response.WriteAsync("Hello World!");
         });

          endpoints.MapHangfireDashboard();

     });
     BackgroundJob.Enqueue(() => Console.WriteLine("测试"));
}

运行程序

 生成数据表

 

 

  访问http://localhost:5000/hangfire

添加Hangfire面板授权

新建MyAuthorizationFilter.cs

public class MyAuthorizationFilter : IDashboardAuthorizationFilter
    {
        public bool Authorize(DashboardContext context)
        {
            var httpContext = context.GetHttpContext();
            string header = httpContext.Request.Headers["Authorization"];//获取授权
            if(header == null)
                return AuthenicateLogin();
            //解析授权
            var authHeader = AuthenticationHeaderValue.Parse(header);
            var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
            var credentials = Encoding.UTF8.GetString(credentialBytes).Split(new[] { ':' }, 2);
            var username = credentials[0];
            var password = credentials[1];
            //验证登录
            if (username == "admin" && password =="123456")
                return true;
            else
                return AuthenicateLogin();
            //跳转简单登录界面
            bool AuthenicateLogin()
            {
                httpContext.Response.StatusCode = 401;
                httpContext.Response.Headers.Append("WWW-Authenticate", "Basic realm=\"Hangfire Dashboard\"");
                context.Response.WriteAsync("Authenticatoin is required.");
                return false;
            }
            
        }
    }

Hangfire面板修改

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {

                 endpoints.MapHangfireDashboard(new DashboardOptions
                 {
                    Authorization = new[] { new MyAuthorizationFilter() }
                 });

                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });

            BackgroundJob.Enqueue(() => Console.WriteLine("测试"));
   }

运行程序

 

 

 

 

 文档链接:https://docs.hangfire.io/en/latest/getting-started/index.html

 

标签:NetCore,app,Hangfire,任务,context,var,endpoints,public
来源: https://www.cnblogs.com/zspwf/p/16229132.html