.Net Core定時排程hangfire:儲存配置
阿新 • • 發佈:2021-07-06
hangfire會將定時任務等資訊儲存起來,有記憶體儲存、快取儲存和資料庫儲存三種方式。
首先在nuget中安裝適配.net core版本的庫Hangfire.AspNetCore。
一、記憶體儲存
在nuget中找到Hangfire.MemoryStorage進行安裝。
之後在Startup檔案中新增如下即可:
public void ConfigureServices(IServiceCollection services) { services.AddHangfire(t => t.UseMemoryStorage()); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseHangfireServer(); }
二、資料庫儲存
資料庫有很多種MySql、Oralce、SqlServer,不過SqlServer是hangfire的預設選擇,所以以此為例在nuget安裝對應的包Hangfire.SqlServer。
其他的資料庫只要找對應的安裝包就行。
支援的資料庫為Microsoft SQL Server 2008R2(任何版本,包括 LocalDB)和更高版本。
但是,僅適用於 Hangfire < 1.5.9:資料庫不使用快照隔離級別,並且READ_COMMITED_SNAPSHOT選項(另一個名稱是Is Read Committed Snapshot On)是 disabled。否則,某些後臺作業可能不會被處理。
具體在Startup檔案中新增如下即可使用:
public void ConfigureServices(IServiceCollection services) { services.AddHangfire(configuration => configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) // 設定資料相容級別 .UseSimpleAssemblyNameTypeSerializer() // 使用簡單程式集名稱型別序列化程式.UseRecommendedSerializerSettings() // 使用推薦的序列化設定 .UseSqlServerStorage(Configuration.GetValue<string>("ConnectionStrings:BaseDb:ConnectionString"), new SqlServerStorageOptions //資料庫設定 { TransactionIsolationLevel = IsolationLevel.ReadCommitted, // 事務隔離級別。預設值為讀提交。 TransactionTimeout = TimeSpan.FromMinutes(1), // 事務超時。預設為1分鐘 JobExpirationCheckInterval = TimeSpan.FromHours(1), // 作業過期檢查間隔(管理過期記錄)。預設為1小時 CountersAggregateInterval = TimeSpan.FromMinutes(5), // 間隔到聚合計數器。預設為5分鐘 PrepareSchemaIfNecessary = true, // 如果設定為true,則建立資料庫表。預設值為true CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), // 命令批處理最大超時時間 SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), // 滑動超時時間 QueuePollInterval = TimeSpan.Zero, // 作業佇列輪詢間隔。預設值為15秒 UseRecommendedIsolationLevel = true, // 是否使用建議的隔離級別 DisableGlobalLocks = true, // 是否禁用全域性鎖,需要遷移到模式7 DashboardJobListLimit = 50000, // 儀表板作業列表上限。預設值為50000 })); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseHangfireServer(); }
啟動之後因為我們設定了PrepareSchemaIfNecessary為true,所以會自動在資料庫中建立資料表儲存資訊。
給hangfire的資料庫連結可以給予最小的許可權,既只操作hangfire相關表的許可權,以提高安全。
三、Redis儲存
使用Redis 作業儲存相比使用 SQL Server 儲存能更快的處理作業。
但是,官方的版本是收費的,有免費版HangFire.Redis.StackExchange。
使用如下:
public void ConfigureServices(IServiceCollection services) { services.AddHangfire(x => { RedisStorageOptions options = new RedisStorageOptions() { Prefix = "hangfire:", //鍵字首 }; x.UseRedisStorage(Configuration.GetValue<string>("ConnectionStrings:Redis:ConnectionString"), options); }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseHangfireServer(); }
檢視redis可以發現,hangfire的資訊已經加入到快取中了