簡體   English   中英

是否可以在Dropwizard中配置多個數據庫連接?

[英]Is it possible to configure multiple database connections in Dropwizard?

我正在開發一些利用Dropwizard的代碼,這將需要我至少連接到兩個不同的數據庫(我也計划使用Hibernate)。 我找不到任何允許我在.yml配置文件的Database塊中配置兩個不同數據庫連接的示例/文檔。 Dropwizard有可能嗎? 如果沒有,人們過去使用的解決方法是什么。 在此先感謝您的幫助!

您可以在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

並在config類中獲取兩個配置詳細信息。

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);

    ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM