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

.NET Core Hangfire任务计划.NET Core Hangfire任务计划

时间:2022-12-15 18:07:07浏览次数:72  
标签:Core app Hangfire context var NET endpoints public

.NET Core Hangfire任务计划

 

安装Hangfire

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

.NET Core Hangfire任务计划.NET Core Hangfire任务计划_数据库

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

<ItemGroup>
<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与Hangfire进行了日志记录集成。Hangfire的日志信息有时非常重要,有助于诊断不同的问题。信息级别允许查看Hangfire的工作情况,警告和更高的日志级别有助于调查问题,建议调整日志级别

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

更新应用程序设置后,打开Startup.cs文件。startup类是.NET CORE应用程序的配置。首先,我们需要导入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("测试"));
}


运行程序

 生成数据表

.NET Core Hangfire任务计划.NET Core Hangfire任务计划_数据库_02

 

 

  访问http://localhost:5000/hangfire

.NET Core Hangfire任务计划.NET Core Hangfire任务计划_数据库_03

添加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("测试"));
}

运行程序

 

.NET Core Hangfire任务计划.NET Core Hangfire任务计划_Core_04

 

 

.NET Core Hangfire任务计划.NET Core Hangfire任务计划_Core_05

 

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



标签:Core,app,Hangfire,context,var,NET,endpoints,public
From: https://blog.51cto.com/u_11990719/5945572

相关文章

  • .netCore 使用 Quartz 实例
    一、参考源文链接 1、https://www.likecs.com/show-897836.html2、https://blog.csdn.net/weixin_43614067/article/details/115373776二、Quartz基本使用publiccla......
  • netstat查看端口
    netstat查看端口netstat-tunlp用于显示tcp,udp的端口和进程等相关情况。netstat查看端口占用语法格式:netstat-tunlp|grep端口号-t(tcp)仅显示tcp相关选项......
  • 第22章:kubernetes弹性伸缩(HPA)
    2弹性伸缩k8s版本v1.202.1传统弹性伸缩的困境从传统意义上,弹性伸缩主要解决的问题是容量规划与实际负载的矛盾。​​​​蓝色水位线表示集群资源容量随着负载的增加不断扩......
  • 如何通过 C#/VB.NET 将 PDF 转为 Word
    众所周知,PDF文档支持特长文件,集成度和安全可靠性都较高,可有效防止他人对PDF内容进行更改,所以在工作中深受大家喜爱。但是在工作中,我们不可避免的会对PDF文档进行修改......
  • .net core 在代码中使用jwt token中的用户信息
    varclaimsIdentity=this.User.IdentityasClaimsIdentity;varuserId=claimsIdentity.FindFirst(ClaimTypes.Name)?.Value;stringuserId=User.FindFirst(ClaimT......
  • centos7端口转发工具rinetd
    1、下载软件wgethttp://li.nux.ro/download/nux/misc/el7/x86_64/rinetd-0.62-9.el7.nux.x86_64.rpm2、安装软件yum-yinstallrinetd-0.62-9.el7.nux.x86_64.rpm3、......
  • 【SQLServer2008】之Telnet以及1433端口设置
    原文链接:https://www.cnblogs.com/Owen-ET/p/5952706.htmlTelnet步骤:一、首先进入Win7控制面板,可以从开始里找到或者在桌面上找到计算机,点击进入里面也可以找到控制面板......
  • linux ethernet driver
    Referencehttps://www.cnblogs.com/YYFaGe/p/16289035.htmlhttps://www.kernel.org/doc/html/latest/driver-api/phy/phy.htmlhttps://simpleiot.blog.csdn.net/art......
  • .net web 大文件上传源代码
    ​ javaweb上传文件上传文件的jsp中的部分上传文件同样可以使用form表单向后端发请求,也可以使用ajax向后端发请求    1.通过form表单向后端发送请求     ......
  • .net core 6.0 使用sqlhelper实现简单的增删改查页面
    一、创建数据表1.根据数据结构文档创建数据表2.数据表创建查询索引二、创建实体类三、创建业务类1.划分业务类结构2.创建默认业务方法四、创建列表......