【问题标题】:Make dynamically HangFire connection string .NetCore动态制作HangFire连接字符串.Net Core
【发布时间】:2020-11-12 23:34:02
【问题描述】:

我有一个使用 HangFire 进行后台作业的项目,我需要动态更改连接字符串,而无需每次我想向任何客户运行此作业时手动更改代码,因为我有很多客户和许多数据库好吧 我已经根据这个解决方案对启动和 DbContext 中的正常连接进行了此操作,并且工作起来就像一个魅力 Dynamically change connection string in Asp.Net Core

我想对 HangFire 连接做同样的事情,这是我现在使用的代码

            services.AddHangfire(configuration => configuration.UseStorage(
            new MySqlStorage("server=127.0.0.1;uid=root;database=0046696-k; Allow User Variables=True",
            new MySqlStorageOptions()
            {
                TransactionIsolationLevel = (System.Transactions.IsolationLevel?)IsolationLevel.ReadCommitted,
                QueuePollInterval = TimeSpan.FromSeconds(15),
                JobExpirationCheckInterval = TimeSpan.FromHours(1),
                CountersAggregateInterval = TimeSpan.FromMinutes(5),
                PrepareSchemaIfNecessary = true,
                DashboardJobListLimit = 50000,
                TransactionTimeout = TimeSpan.FromMinutes(1),
                TablesPrefix = "Hangfire"
            })));
        services.AddHangfireServer();

【问题讨论】:

标签: c# linq asp.net-core hangfire


【解决方案1】:

不要对连接字符串进行硬编码。

将其存储在 appsettings.json 文件中

例如

{
  "ConnectionStrings": {
    "Hangfire": "server=127.0.0.1;uid=root;database=0046696-k; Allow User Variables=True"
  }

  /* other settings */
}  

并在启动时加载它。

//...Assume IConfiguration Configuration is loaded

//...

string connectionString = Configuration.GetConnectionString("Hangfire"); //<-- NOTE

services.AddHangfire(configuration => configuration.UseStorage(
    new MySqlStorage(connectionString, //<-- NOTE
    new MySqlStorageOptions() {
        TransactionIsolationLevel = (System.Transactions.IsolationLevel?)IsolationLevel.ReadCommitted,
        QueuePollInterval = TimeSpan.FromSeconds(15),
        JobExpirationCheckInterval = TimeSpan.FromHours(1),
        CountersAggregateInterval = TimeSpan.FromMinutes(5),
        PrepareSchemaIfNecessary = true,
        DashboardJobListLimit = 50000,
        TransactionTimeout = TimeSpan.FromMinutes(1),
        TablesPrefix = "Hangfire"
    })));

services.AddHangfireServer();

//...

这样您只需要根据需要编辑设置文件。

如果选项也需要动态更改,则在设置中添加一个部分以保存所需的选项并将它们加载到启动中。

【讨论】:

  • 没想到这么简单,谢谢
猜你喜欢
  • 2016-10-02
  • 1970-01-01
  • 1970-01-01
  • 2017-05-06
  • 2019-01-07
  • 1970-01-01
  • 2016-08-17
  • 2018-05-28
相关资源
最近更新 更多