ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

.NetCore Hangfire任务计划

2022-05-06 16:34:12  阅读:170  来源: 互联网

标签:NetCore app Hangfire 任务 context var endpoints public


安装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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有