【问题标题】:Is it possible to configure multiple database connections in Dropwizard?是否可以在 Dropwizard 中配置多个数据库连接?
【发布时间】:2014-01-18 23:33:36
【问题描述】:

我正在编写一些利用 Dropwizard 的代码,这将要求我需要连接到至少两个不同的数据库(我也计划使用 Hibernate)。我找不到任何允许我在 .yml 配置文件的 Database 块中配置两个不同数据库连接的示例/文档。这在 Dropwizard 中可行吗?如果没有,人们过去使用的解决方法是什么。提前感谢您的帮助!

【问题讨论】:

  • 写信给 Dropwizard 支持并询问他们或在他们的论坛上提问。
  • 谢谢,我会在那里发帖。问候

标签: database hibernate dropwizard


【解决方案1】:

您可以在 dropwizard 中配置多个数据库。在 config.yml 中你可以有多个这样的数据库配置。

数据库1:

driverClass: org.postgresql.Driver
user: user
password: pwd
url: jdbc:postgresql://localhost:5432/db1
validationQuery: select 1
minSize: 2
maxSize: 8

数据库2:

driverClass: org.postgresql.Driver
user: user
password: pwd
url: jdbc:postgresql://localhost:5432/db2
validationQuery: select 1
minSize: 2
maxSize: 8

并在配置类中获取两个配置详细信息。

public class DBConfig extends Configuration {

    private DatabaseConfiguration database1;
    private DatabaseConfiguration database2;

    public DatabaseConfiguration getDatabase1() {
        return database1;
    }

    public DatabaseConfiguration getDatabase2() {
        return database2;
    }
}

并在您的服务中配置哪个 Dao 使用哪个数据库。

@Override
public void run(MyConfiguration configuration,
                Environment environment) throws ClassNotFoundException {
    ... 

    final DBIFactory factory = new DBIFactory();

    // Note that the name parameter when creating the DBIs must be different
    // Otherwise you get an IllegalArgumentException
    final DBI jdbi1 = factory.build(
            environment, configuration.getUserDatabase(), "db1");
    final DBI jdbi2 = factory.build(
            environment, configuration.getItemDatabase(), "db2");

    final MyFirstDAO firstDAO = jdbi1.onDemand(MyFirstDAO.class);
    final MySecondDAO secondDAO = jdbi2.onDemand(MySecondDAO.class);

    ...
}

【讨论】:

  • 我们如何决定用户在登录应用或webapp时连接哪个数据库?用户是否可以切换到特定的数据库?
猜你喜欢
  • 2018-03-11
  • 1970-01-01
  • 2015-05-13
  • 2011-03-17
  • 2012-01-08
  • 2020-04-28
  • 2013-08-06
  • 2019-06-17
  • 1970-01-01
相关资源
最近更新 更多