gpt4 book ai didi

java - 动态数据源作为 Spring Boot + Hibernate 中的第二个数据源

转载 作者:搜寻专家 更新时间:2023-11-01 03:33:08 25 4
gpt4 key购买 nike

我有一个关于如何在 Spring Boot 应用程序中处理两个不同数据源的问题。

用例:

I have one main repository (db) which must be connected all the time (application scope), i have no problem with that, having TransactionManager and EntityManager.

The second database connection should be only request scoped, with dynamic credentials gathered from an httpRequest.

数据源均来自PostgreSQL。

这可能吗?如果是,实现该目标的最佳方法是什么。

感谢您的帮助。

最佳答案

这是两个数据源模式的有趣转折!

您的第二个数据源必须根据应用程序外部的信息进行解析,因此您将无法使用 Spring 应用程序上下文。

您可以在 Spring 中以编程方式配置数据源,本问答中对此进行了介绍:

Configure DataSource programmatically in Spring Boot

您的情况略有不同,因为凭据将在运行时解析,但可以使用相同的想法。

  1. 确保您拥有 Spring JDBC 依赖项。
    <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
  1. 使用 DataSourceBuilder,使用您的凭据构造一个新的 DataSource 对象
public DataSource getDataSource(String user, String password) {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.url(DBB_URL);
dataSourceBuilder.username(user);
dataSourceBuilder.password(password);
return dataSourceBuilder.build();
}

然后将其用作代码的数据源。您将无法 Autowiring 它,因此您将想出一个合理的策略来确定何时在 JDBC 方法中构建数据源,并以一种允许您实现事务完整性的方式将其与 Spring JdbcTemplate 一起使用正在寻找为了。

您还没有指定其他注意事项。此策略假定您对两个数据源使用相同的 JDBC 驱动程序。如果您使用不同的数据库,则必须为这些库添加依赖项,然后为您的动态数据源指定驱动程序类。

关于java - 动态数据源作为 Spring Boot + Hibernate 中的第二个数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42087518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com