为多租户应用程序初始化Hangfire服务器

时间:2018-01-01 08:05:22

标签: c# asp.net-mvc multi-tenant hangfire

我面临着为多租户应用添加Hangfire服务器的问题。在我的应用程序启动中,我循环遍历所有租户并初始化并为每个租户添加一组作业。它在每个租户数据库中添加服务器,但作业仅添加到第一个租户数据库。我在其他租户数据库和仪表板中看不到任何工作。以下是我正在尝试的代码:

foreach (var tenant in TenantConvention.GetTenants())
            {

                GlobalConfiguration.Configuration
                 .UseSqlServerStorage(DbServer.GetConnectionString(tenant));

                var sqlStorage = new SqlServerStorage(DbServer.GetConnectionString(tenant));

                app.UseHangfireDashboard($"/dashboard/{tenant}-Jobs", new DashboardOptions
                {
                    Authorization = new[] { new HangfireAuthFilter() }

                }, sqlStorage);

                var options = new BackgroundJobServerOptions
                {                   
                    ServerName = tenant//string.Format("{0}.{1}", tenant, Guid.NewGuid().ToString())
                };

                var jobStorage = JobStorage.Current;
                app.UseHangfireServer(options, jobStorage);               

                var schedulars = ObjectFactory.GetAllInstances();
                foreach (var schedular in schedulars) {
                    schedular.Init();
                }

            }

任何帮助将不胜感激。 感谢

1 个答案:

答案 0 :(得分:1)

默认情况下不支持,因此您应使用EnqueuedState,如下所示:

  Hangfire.States.IState state = new Hangfire.States.EnqueuedState
                {
                    Queue = serverName
                };  
  client.Create(() => Console.WriteLine(serverName), state); 

所以要真正测试我在SQL Server中创建了两个名为DB1DB2的数据库,并测试下面的代码(Works nice):

string[] connections = new string[] {
                "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=DB1",
                "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=DB2"}; 
foreach (string strConnection in connections)
     {
          string serverName = "str" + DateTime.Now.Ticks;
          var sqlStorage = new Hangfire.SqlServer.SqlServerStorage(strConnection);
          var options = new BackgroundJobServerOptions
            {
                ServerName =serverName  
            };
          JobStorage.Current = sqlStorage;
          IBackgroundJobClient client = new BackgroundJobClient();
          Hangfire.States.IState state = new Hangfire.States.EnqueuedState
                {
                    Queue = serverName
                };  
          client.Create(() => Console.WriteLine(serverName), state); 
     }

以上代码是运行后的示例我已经看到创建了两个作业,但在不同的Db中如下截图所示:

enter image description here