【问题标题】:Multiple datasources in Spring Boot Repository Annotated InterfaceSpring Boot Repository Annotated Interface 中的多个数据源
【发布时间】:2017-01-08 23:35:34
【问题描述】:

我的应用程序基于 Spring Boot、Hibernate、MySQL,使用 Spring Data JPA 来拼接它们。

用例是使用从数据库节点进行繁重的读取操作,以避免从主 mysql 节点提供所有流量。实现这一点的一种方法是让多个实体管理器指向不同的数据源(一个指向主节点,另一个指向从节点)。在下面的 SO 问题和博客中已经很好地解释了这种方式。

Spring Boot, Spring Data JPA with multiple DataSources

https://scattercode.co.uk/2016/01/05/multiple-databases-with-spring-boot-and-spring-data-jpa/

我陷入困境的地方是了解是否有一种方法可以在我的 Repository Annotated Interface 中为不同的用例注入不同的实体管理器。

我认为可以做到的唯一方法是使用自定义实现扩展存储库,该实现使用自定义实体管理器,并使用下面的相关persistenceContext注释。

public interface CustomerRepository extends JpaRepository<Customer, Integer>, MyCustomCustomerRepository{
}

public class MyCustomCustomerRepositoryImpl implements MyCustomCustomerRepository {

        @PersistenceContext(unitName = "entityManagerFactoryTwo")
        EntityManager entityManager;
}

我想避免执行此自定义实现。任何有关解决此用例的帮助(我觉得应该很常见)将不胜感激。

注意:两个数据库中的实体相同,因此为实体扫描和类似解决方案提供单独的包可能不起作用。

【问题讨论】:

  • this sample 有帮助吗?
  • 您分享的Demo在不同的数据库中有两个不同的实体。在这种情况下使用两个实体管理器时,避免冲突变得更容易。对我来说,无论我们将它们用于主数据库还是从数据库,实体都保持不变。

标签: spring hibernate spring-boot spring-data spring-data-jpa


【解决方案1】:

这是一个不错的示例,您可以使用: dynamic-datasource-routing-with-spring。 在里面你可以找到一个AbstractRoutingDatasource + 一个自定义注释的拦截器,它将服务方法连接到所需的数据库。 但是,您可以显式使用数据源开关。

【讨论】:

  • 虽然示例使用 xml 配置就够了,而且我的项目主要是注释驱动的,但提供的答案为我提供了有关如何实现该功能的良好背景。谢谢:)
【解决方案2】:

以下是显示差异的拉取请求,以及我如何使其与大多数配置注释驱动而不是 xml 一起工作。它基于上面cra6的答案。即使用 spring 的 RoutingDataSource 功能。

https://github.com/himanshuvirmani/rest-webservice-sample/pull/1/files

【讨论】:

    猜你喜欢
    • 2016-01-28
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 2023-03-20
    • 2021-12-08
    • 1970-01-01
    • 2020-01-15
    • 2014-12-06
    相关资源
    最近更新 更多