SpringBoot 项目配置多数据源

本贴最后更新于 530 天前,其中的信息可能已经时移俗易

如果需要在同一个 Spring Boot 应用程序中同时使用 PostgreSQL 和 Oracle 数据库,你可以配置多个数据源来实现这一目标。

添加依赖

dependencies {
    implementation 'org.postgresql:postgresql:42.3.1'
    implementation 'com.oracle.database.jdbc:ojdbc8:19.3.0.0'
    //其他依赖项
}


配置文件

spring:
  primary:
    datasource:
      driver-class-name: org.postgresql.Driver
      jdbc-url: jdbc:postgresql://localhost:5432/nap
      username: xxx
      password: xxx
      test-on-borrow: true
      validationQuery: SELECT 1
      name: HikariPool-1
      minimum-idle: 15
      maximum-pool-size: 30
      idle-timeout: 600000
      max-lefetime: 1800000
      connection-timeout: 30000
  secondary:
    datasource:
      driver-class-name: oracle.jdbc.OracleDriver
      jdbc-url: jdbc:oracle:thin:@//localhost:1521/odrd
      username: xxx
      password: xxx
      test-on-borrow: true
      validationQuery: SELECT 1
      name: HikariPool-2
      minimum-idle: 15
      maximum-pool-size: 30
      idle-timeout: 600000
      max-lefetime: 1800000
      connection-timeout: 30000

数据源配置

/**
 * 数据源的配置
 */
@Configuration
public class DataSourceConfig {
    private static Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);

    @Bean(name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @ConfigurationProperties(prefix = "spring.primary.datasource")
    @Primary
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondaryDataSource")
    @Qualifier("secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.secondary.datasource")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "primaryJdbcTemplate")
    @Primary
    public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") DataSource primaryDataSource) {
        return new JdbcTemplate(primaryDataSource);
    }

    @Bean(name = "secondaryJdbcTemplate")
    public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") DataSource secondaryDataSource) {
        return new JdbcTemplate(secondaryDataSource);
    }


}

配置实体管理

配置完数据源之后,还需要配置一些额外的东西,例如 实体Repository 的包路径,hibernate 以及 实体管理器 等一系列需要的 bean

/**
 * 数据源一
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryPrimary",
        transactionManagerRef = "transactionManagerPrimary",
        basePackages = {"net.skycloud.mtkadaptor.basedata.repository", "net.skycloud.mtkadaptor.order.repository",
                "net.skycloud.mtkadaptor.subnet.repository","net.skycloud.mtkadaptor.user.repository"})
//设置Repository所在位置
public class PrimaryConfig {
    @Autowired
    @Qualifier("primaryDataSource")
    private DataSource primaryDataSource;

    @Primary
    @Bean(name = "entityManagerPrimary")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return Objects.requireNonNull(entityManagerFactoryPrimary(builder).getObject()).createEntityManager();
    }

    @Primary
    @Bean(name = "entityManagerFactoryPrimary")
    //设置实体所在包
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(primaryDataSource)
                .properties(getVendorProperties())
                .packages("net.skycloud.mtkadaptor.basedata.model", "net.skycloud.mtkadaptor.order.model",
                        "net.skycloud.mtkadaptor.subnet.model","net.skycloud.mtkadaptor.user.model","net.skycloud.common.model")
                .persistenceUnit("primaryPersistenceUnit")
                .build();
    }
    //配置hibernate信息 方言等
    private Map<String, String> getVendorProperties() {
        Map<String, String> jpaProperties = new HashMap<>(16);
        jpaProperties.put("hibernate.hbm2ddl.auto", "none");
        jpaProperties.put("hibernate.show_sql", "false");
        jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
        jpaProperties.put("hibernate.implicit_naming_strategy", SpringImplicitNamingStrategy.class.getName());
        jpaProperties.put("hibernate.physical_naming_strategy", SpringPhysicalNamingStrategy.class.getName());;
        return jpaProperties;
    }

    @Primary
    @Bean(name = "transactionManagerPrimary")
    //配置事物管理器
    public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
    }
}

/**
 * 数据源二
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactorySecondary",
        transactionManagerRef = "transactionManagerSecondary", basePackages = {"net.skycloud.mtkadaptor.odr"})
public class SecondaryConfig {
    @Autowired
    @Qualifier("secondaryDataSource")
    private DataSource secondaryDataSource;

    @Bean(name = "entityManagerSecondary")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return Objects.requireNonNull(entityManagerFactorySecondary(builder).getObject()).createEntityManager();
    }

    @Bean(name = "entityManagerFactorySecondary")
    public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(secondaryDataSource)
                .properties(getVendorProperties(secondaryDataSource))
                .packages("net.skycloud.mtkadaptor.odr")
                .persistenceUnit("secondaryPersistenceUnit")
                .build();
    }


    private Map<String, String> getVendorProperties(DataSource dataSource) {
        Map<String, String> jpaProperties = new HashMap<>(16);
        jpaProperties.put("hibernate.hbm2ddl.auto", "none");
        jpaProperties.put("hibernate.show_sql", "false");
        jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
        return jpaProperties;
    }

    @Bean(name = "transactionManagerSecondary")
    PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
    }
}

配置好之后,你就可以在对应的包下面开发 EntityRepository 了,至此多数据源的配置就完成了。

  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3187 引用 • 8213 回帖
  • Spring

    Spring 是一个开源框架,是于 2003 年兴起的一个轻量级的 Java 开发框架,由 Rod Johnson 在其著作《Expert One-On-One J2EE Development and Design》中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 JavaEE 应用程序开发提供集成的框架。

    944 引用 • 1459 回帖 • 18 关注
  • 数据库

    据说 99% 的性能瓶颈都在数据库。

    340 引用 • 708 回帖
1 操作
Gakkiyomi2019 在 2023-06-09 20:15:01 更新了该帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...