如何在 mongodb 的 .net 核心中使用 hangfire?

How to use hangfire in .net core with mongodb?

我想在注册表过程中使用 Hangfire 进行后台作业,但是我找不到 Startup.cs Hangfire.mongo 的文件代码。

正在启动中class 在 ConfigureServices 方法中 添加

//you will use some way to get your connection string
var mongoConnection = Configuration.GetConnectionString("MongoDBAtlasJaken");
var migrationOptions = new MongoMigrationOptions
{
    Strategy = MongoMigrationStrategy.Drop,
    BackupStrategy = MongoBackupStrategy.Collections
};

services.AddHangfire(config =>
{
    config.SetDataCompatibilityLevel(CompatibilityLevel.Version_170);
    config.UseSimpleAssemblyNameTypeSerializer();
    config.UseRecommendedSerializerSettings();
    config.UseMongoStorage(mongoConnection, "Hangfire",new MongoStorageOptions {   MigrationOptions = migrationOptions });

});
services.AddHangfireServer();

在Configure方法中可以根据需要添加

app.UseHangfireDashboard();

只是对此线程的更新,

从 v0.7.11 开始,MongoMigrationOptions 已经更新,不再包含策略。根据 release notes,您现在必须使用 MigrationStrategy 而不是策略。此外,您用于这些的值也不同。请参阅下面的示例。

var migrationOptions = new MongoMigrationOptions
{
    MigrationStrategy = new MigrateMongoMigrationStrategy(),
    BackupStrategy = new CollectionMongoBackupStrategy()
};

@Graeme 的回答适用于旧版本的 Hangfire。对于新版本,

  1. MigrationBackup 策略从枚举更改为 class。

     var migrationOptions = new MongoMigrationOptions
     {
         MigrationStrategy = new DropMongoMigrationStrategy(),
         BackupStrategy = new CollectionMongoBackupStrategy()
     };
    
  2. UseMongoStorage 方法不再接受集合名称。

     services.AddHangfire(config =>
     {
         config.SetDataCompatibilityLevel(CompatibilityLevel.Version_170);
         config.UseSimpleAssemblyNameTypeSerializer();
         config.UseRecommendedSerializerSettings();
         config.UseMongoStorage(mongoConnection, new MongoStorageOptions { MigrationOptions = migrationOptions, CheckConnection = false });
     });
    

    services.AddHangfireServer();