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

问题描述 投票:1回答:1

我面临着为多租户应用程序添加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();
                }

            }

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

c# asp.net-mvc multi-tenant hangfire
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.