循序渐进学.Net Core Web Api开发系列【17】:.Net core自动作业之Hangfire
nuget搜索:Hangfire
安装即可,这里我选择的是 1.7.0-beta1 版本
我是用这个集成到了 mvc api里
这里需要在 Startup 文件里进行如下配置
在配置方法 ConfigureServices 里配置数据库,这是用的是sqlserver数据库初始化
var hangfireConnStr = _configuration["AppSettings:HangfireConnectionString"]; services.AddHangfire(configuration => configuration.UseSqlServerStorage(hangfireConnStr));
如果数据库是mysql,使用下面语句初始化,需要引用 Hangfire.MySql
var hangfireMysqlConnStr = _configuration["AppSettings:HangfireMysqlConnectionString"]; services.AddHangfire(configuration => configuration.UseStorage( new MySqlStorage( hangfireMysqlConnStr, new MySqlStorageOptions { TransactionIsolationLevel = IsolationLevel.ReadCommitted, QueuePollInterval = TimeSpan.FromSeconds(15), JobExpirationCheckInterval = TimeSpan.FromHours(1), CountersAggregateInterval = TimeSpan.FromMinutes(5), PrepareSchemaIfNecessary = true, DashboardJobListLimit = 50000, TransactionTimeout = TimeSpan.FromMinutes(1), TablesPrefix = "" })));
在配置方法 Configure 里需要配置下管理员后台
app.UseHangfireServer();
app.UseHangfireDashboard();
这样我们就可以通过后台操作管理作业了
地址如下
https://localhost:5001/hangfire
这里可以看到正在跑的作业和执行情况
不过这个后台只能在服务器本机上访问,为了保证安全,无法通过域名访问操作
添加调用代码很简单,在每次系统启动的时候,配置如下,如果没有添加;有了就更新
RecurringJob.AddOrUpdate(() => UpdateMerchIndex(), Cron.MinuteInterval(3));
这里是指每隔三分钟调用一次 UpdateMerchIndex() 方法。
是不是很简单呢
数据库需要初始化几个表
这里附送数据库初始化建表SQL语句
sqlserver
USE [GEDU_Hangfire] GO /****** Object: Table [HangFire].[Job] Script Date: 01/22/2019 14:16:29 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [HangFire].[Job]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [StateId] [bigint] NULL, [StateName] [nvarchar](20) NULL, [InvocationData] [nvarchar](max) NOT NULL, [Arguments] [nvarchar](max) NOT NULL, [CreatedAt] [datetime] NOT NULL, [ExpireAt] [datetime] NULL, CONSTRAINT [PK_HangFire_Job] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO /****** Object: Table [HangFire].[Hash] Script Date: 01/22/2019 14:16:29 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [HangFire].[Hash]( [Key] [nvarchar](100) NOT NULL, [Field] [nvarchar](100) NOT NULL, [Value] [nvarchar](max) NULL, [ExpireAt] [datetime2](7) NULL, CONSTRAINT [PK_HangFire_Hash] PRIMARY KEY CLUSTERED ( [Key] ASC, [Field] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO /****** Object: Table [HangFire].[Counter] Script Date: 01/22/2019 14:16:29 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [HangFire].[Counter]( [Key] [nvarchar](100) NOT NULL, [Value] [int] NOT NULL, [ExpireAt] [datetime] NULL ) ON [PRIMARY] GO /****** Object: Table [HangFire].[AggregatedCounter] Script Date: 01/22/2019 14:16:29 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [HangFire].[AggregatedCounter]( [Key] [nvarchar](100) NOT NULL, [Value] [bigint] NOT NULL, [ExpireAt] [datetime] NULL, CONSTRAINT [PK_HangFire_CounterAggregated] PRIMARY KEY CLUSTERED ( [Key] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO /****** Object: Table [HangFire].[Set] Script Date: 01/22/2019 14:16:29 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [HangFire].[Set]( [Key] [nvarchar](100) NOT NULL, [Score] [float] NOT NULL, [Value] [nvarchar](256) NOT NULL, [ExpireAt] [datetime] NULL, CONSTRAINT [PK_HangFire_Set] PRIMARY KEY CLUSTERED ( [Key] ASC, [Value] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO /****** Object: Table [HangFire].[Server] Script Date: 01/22/2019 14:16:29 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [HangFire].[Server]( [Id] [nvarchar](100) NOT NULL, [Data] [nvarchar](max) NULL, [LastHeartbeat] [datetime] NOT NULL, CONSTRAINT [PK_HangFire_Server] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO /****** Object: Table [HangFire].[Schema] Script Date: 01/22/2019 14:16:29 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [HangFire].[Schema]( [Version] [int] NOT NULL, CONSTRAINT [PK_HangFire_Schema] PRIMARY KEY CLUSTERED ( [Version] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO /****** Object: Table [HangFire].[List] Script Date: 01/22/2019 14:16:29 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [HangFire].[List]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [Key] [nvarchar](100) NOT NULL, [Value] [nvarchar](max) NULL, [ExpireAt] [datetime] NULL, CONSTRAINT [PK_HangFire_List] PRIMARY KEY CLUSTERED ( [Key] ASC, [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO /****** Object: Table [HangFire].[JobQueue] Script Date: 01/22/2019 14:16:29 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [HangFire].[JobQueue]( [Id] [int] IDENTITY(1,1) NOT NULL, [JobId] [bigint] NOT NULL, [Queue] [nvarchar](50) NOT NULL, [FetchedAt] [datetime] NULL, CONSTRAINT [PK_HangFire_JobQueue] PRIMARY KEY CLUSTERED ( [Queue] ASC, [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO /****** Object: Table [HangFire].[State] Script Date: 01/22/2019 14:16:29 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [HangFire].[State]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [JobId] [bigint] NOT NULL, [Name] [nvarchar](20) NOT NULL, [Reason] [nvarchar](100) NULL, [CreatedAt] [datetime] NOT NULL, [Data] [nvarchar](max) NULL, CONSTRAINT [PK_HangFire_State] PRIMARY KEY CLUSTERED ( [JobId] ASC, [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO /****** Object: Table [HangFire].[JobParameter] Script Date: 01/22/2019 14:16:29 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [HangFire].[JobParameter]( [JobId] [bigint] NOT NULL, [Name] [nvarchar](40) NOT NULL, [Value] [nvarchar](max) NULL, CONSTRAINT [PK_HangFire_JobParameter] PRIMARY KEY CLUSTERED ( [JobId] ASC, [Name] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO /****** Object: ForeignKey [FK_HangFire_JobParameter_Job] Script Date: 01/22/2019 14:16:29 ******/ ALTER TABLE [HangFire].[JobParameter] WITH CHECK ADD CONSTRAINT [FK_HangFire_JobParameter_Job] FOREIGN KEY([JobId]) REFERENCES [HangFire].[Job] ([Id]) ON UPDATE CASCADE ON DELETE CASCADE GO ALTER TABLE [HangFire].[JobParameter] CHECK CONSTRAINT [FK_HangFire_JobParameter_Job] GO /****** Object: ForeignKey [FK_HangFire_State_Job] Script Date: 01/22/2019 14:16:29 ******/ ALTER TABLE [HangFire].[State] WITH CHECK ADD CONSTRAINT [FK_HangFire_State_Job] FOREIGN KEY([JobId]) REFERENCES [HangFire].[Job] ([Id]) ON UPDATE CASCADE ON DELETE CASCADE GO ALTER TABLE [HangFire].[State] CHECK CONSTRAINT [FK_HangFire_State_Job] GO
mysql
/* Navicat Premium Data TransferSource Server : mysql47.93.198.115
Source Server Type : MySQL
Source Server Version : 50562
Source Host : 47.93.198.115:3306
Source Schema : gedu_hangfireTarget Server Type : MySQL
Target Server Version : 50562
File Encoding : 65001Date: 22/01/2019 14:17:37
*/SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for aggregatedcounter
-- ----------------------------
DROP TABLE IF EXISTSaggregatedcounter
;
CREATE TABLEaggregatedcounter
(
Id
int(11) NOT NULL AUTO_INCREMENT,
</span><span style="color: #0000ff;">Key</span>
varchar(100) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
Value
int(11) NOT NULL,
ExpireAt
datetime NULL DEFAULT NULL,
PRIMARY KEY (Id
) USING BTREE,
UNIQUE INDEXIX_CounterAggregated_Key
(<span style="color: #0000ff;">Key</span><span style="color: #000000;">
) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3482 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Compact;-- ----------------------------
-- Table structure for counter
-- ----------------------------
DROP TABLE IF EXISTScounter
;
CREATE TABLEcounter
(
Id
int(11) NOT NULL AUTO_INCREMENT,
</span><span style="color: #0000ff;">Key</span>
varchar(100) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
Value
int(11) NOT NULL,
ExpireAt
datetime NULL DEFAULT NULL,
PRIMARY KEY (Id
) USING BTREE,
INDEXIX_Counter_Key
(<span style="color: #0000ff;">Key</span><span style="color: #000000;">
) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 17107 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Compact;-- ----------------------------
-- Table structure for distributedlock
-- ----------------------------
DROP TABLE IF EXISTSdistributedlock
;
CREATE TABLEdistributedlock
(
Resource
varchar(100) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
CreatedAt
datetime NOT NULL
) ENGINE = InnoDB CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Compact;-- ----------------------------
-- Table structure for hash
-- ----------------------------
DROP TABLE IF EXISTShash
;
CREATE TABLEhash
(
Id
int(11) NOT NULL AUTO_INCREMENT,
</span><span style="color: #0000ff;">Key</span>
varchar(100) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
Field
varchar(40) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
Value
longtext CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL,
ExpireAt
datetime NULL DEFAULT NULL,
PRIMARY KEY (Id
) USING BTREE,
UNIQUE INDEXIX_Hash_Key_Field
(<span style="color: #0000ff;">Key</span><span style="color: #000000;">
,Field
) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 29028 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Compact;-- ----------------------------
-- Table structure for job
-- ----------------------------
DROP TABLE IF EXISTSjob
;
CREATE TABLEjob
(
Id
int(11) NOT NULL AUTO_INCREMENT,
StateId
int(11) NULL DEFAULT NULL,
StateName
varchar(20) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
InvocationData
longtext CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
Arguments
longtext CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
CreatedAt
datetime NOT NULL,
ExpireAt
datetime NULL DEFAULT NULL,
PRIMARY KEY (Id
) USING BTREE,
INDEXIX_Job_StateName
(StateName
) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5703 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Compact;-- ----------------------------
-- Table structure for jobparameter
-- ----------------------------
DROP TABLE IF EXISTSjobparameter
;
CREATE TABLEjobparameter
(
Id
int(11) NOT NULL AUTO_INCREMENT,
JobId
int(11) NOT NULL,
Name
varchar(40) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
Value
longtext CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL,
PRIMARY KEY (Id
) USING BTREE,
UNIQUE INDEXIX_JobParameter_JobId_Name
(JobId
,Name
) USING BTREE,
INDEXFK_JobParameter_Job
(JobId
) USING BTREE,
CONSTRAINTFK_JobParameter_Job
FOREIGN KEY (JobId
) REFERENCESjob
(Id
) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB AUTO_INCREMENT = 17107 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Compact;-- ----------------------------
-- Table structure for jobqueue
-- ----------------------------
DROP TABLE IF EXISTSjobqueue
;
CREATE TABLEjobqueue
(
Id
int(11) NOT NULL AUTO_INCREMENT,
JobId
int(11) NOT NULL,
Queue
varchar(50) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
FetchedAt
datetime NULL DEFAULT NULL,
FetchToken
varchar(36) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
PRIMARY KEY (Id
) USING BTREE,
INDEXIX_JobQueue_QueueAndFetchedAt
(Queue
,FetchedAt
) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5703 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Compact;-- ----------------------------
-- Table structure for jobstate
-- ----------------------------
DROP TABLE IF EXISTSjobstate
;
CREATE TABLEjobstate
(
Id
int(11) NOT NULL AUTO_INCREMENT,
JobId
int(11) NOT NULL,
Name
varchar(20) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
Reason
varchar(100) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
CreatedAt
datetime NOT NULL,
Data
longtext CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL,
PRIMARY KEY (Id
) USING BTREE,
INDEXFK_JobState_Job
(JobId
) USING BTREE,
CONSTRAINTFK_JobState_Job
FOREIGN KEY (JobId
) REFERENCESjob
(Id
) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Compact;-- ----------------------------
-- Table structure for list
-- ----------------------------
DROP TABLE IF EXISTSlist
;
CREATE TABLElist
(
Id
int(11) NOT NULL AUTO_INCREMENT,
</span><span style="color: #0000ff;">Key</span>
varchar(100) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
Value
longtext CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL,
ExpireAt
datetime NULL DEFAULT NULL,
PRIMARY KEY (Id
) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Compact;-- ----------------------------
-- Table structure for server
-- ----------------------------
DROP TABLE IF EXISTSserver
;
CREATE TABLEserver
(
Id
varchar(100) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
Data
longtext CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
LastHeartbeat
datetime NULL DEFAULT NULL,
PRIMARY KEY (Id
) USING BTREE
) ENGINE = InnoDB CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Compact;-- ----------------------------
-- Table structure for set
-- ----------------------------
DROP TABLE IF EXISTS<span style="color: #0000ff;">set</span><span style="color: #000000;">
;
CREATE TABLE<span style="color: #0000ff;">set</span><span style="color: #000000;">
(
Id
int(11) NOT NULL AUTO_INCREMENT,
</span><span style="color: #0000ff;">Key</span>
varchar(100) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
Value
varchar(256) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
Score
float NOT NULL,
ExpireAt
datetime NULL DEFAULT NULL,
PRIMARY KEY (Id
) USING BTREE,
UNIQUE INDEXIX_Set_Key_Value
(<span style="color: #0000ff;">Key</span><span style="color: #000000;">
,Value
) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 95 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Compact;-- ----------------------------
-- Table structure for state
-- ----------------------------
DROP TABLE IF EXISTSstate
;
CREATE TABLEstate
(
Id
int(11) NOT NULL AUTO_INCREMENT,
JobId
int(11) NOT NULL,
Name
varchar(20) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
Reason
varchar(100) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
CreatedAt
datetime NOT NULL,
Data
longtext CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL,
PRIMARY KEY (Id
) USING BTREE,
INDEXFK_HangFire_State_Job
(JobId
) USING BTREE,
CONSTRAINTFK_HangFire_State_Job
FOREIGN KEY (JobId
) REFERENCESjob
(Id
) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB AUTO_INCREMENT = 17108 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Compact;SET FOREIGN_KEY_CHECKS = 1;
redis配置(Startup.cs 文件里的 ConfigureServices)
//注入Hangfire服务 redis var hangfireRedisConnStr = Configuration["AppSettings:HangfireRedisConnectionString"]; _redis = ConnectionMultiplexer.Connect(hangfireRedisConnStr); var prefix = Configuration["AppSettings:HangfireRedisPrefixName"]; var option = new RedisStorageOptions { Prefix = prefix, Db = 0, }; if (int.TryParse(Configuration["AppSettings:HangfireRedisDefaultDatabse"], out int dfaultdb)) { if (dfaultdb >= 0 && dfaultdb <= 15) { option.Db = dfaultdb; } } services.AddHangfire(config => config.UseRedisStorage(_redis, option));
配置文件
{ "Logging": { "IncludeScopes": false, "Debug": { "LogLevel": { "Default": "Warning" } }, "Console": { "LogLevel": { "Default": "Warning" } } }, "AppSettings": { "HangfireRedisConnectionString": "127.0.0.1:6379,password=,defaultDatabase=1,ssl=false,writeBuffer=10240", "HangfireRedisPrefixName": "{hangfire_muniumini}:", "HangfireRedisDefaultDatabse": "1", "RedisConnectionString": "127.0.0.1:6379,password=,defaultDatabase=1,poolsize=50,ssl=false,writeBuffer=10240", "UseSwagger": "true" }, "AllowedHosts": "*" }
其中AppSetting里的配置说明
HangfireRedisConnectionString(连接字符串,格式参考上面的配置文件)
HangfireRedisPrefixName(redis的字典集名称)
HangfireRedisDefaultDatabse(redis默认数据库序号)
搞定