java 卡宴4.1 -单一运行时间,多个数据节点具有不同的URL和凭证

toiithl6  于 2022-12-02  发布在  Java
关注(0)|答案(1)|浏览(127)

我有两个不同的数据库被一个应用程序使用。在xml文件中,我可以用不同的url和凭据声明两个节点,没有问题。
有没有办法在代码中做到这一点?不创建2个运行时。

70gysomp

70gysomp1#

可以通过封装在模块中的属性来实现:

ServerRuntime.builder()
  .addModule(b -> ServerModule.contributeProperties(b)
    .put("cayenne.jdbc.url.project.node1", "jdbc:url1")
    .put("cayenne.jdbc.url.project.node2", "jdbc:url2")
    // similarly add properties for driver, user, password, etc.
  )
  .build();

或者,对于Modeler中的每个DataNode,您可以设置一个自定义的“DataSource Factory”,将其指向您自己的Java类,如下所示:

public class MyDataSourceFactory implements DataSourceFactory {
    
    @Override
    public DataSource getDataSource(DataNodeDescriptor nd) throws Exception {
        DataSourceInfo info = nd.getDataSourceDescriptor();

        // use the configuration in the DataSourceInfo and/or supplement it 
        // your own values
        ...

        // Create a DataSource
        Driver driver = (Driver)objectFactory.getJavaClass(driverClass).newInstance();
        return DataSourceBuilder
            .url(url)
            .driver(driver)
            .userName(username)
            .password(password)
            .pool(minConnections, maxConnections)
            .maxQueueWaitTime(maxQueueWaitTime)
            .validationQuery(validationQuery)
            .build();
    }
}

相关问题