欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot +jpa配置双数据源

程序员文章站 2022-05-24 16:11:50
...

业务需求需要在一个项目里配置两个数据源。项目使用的是springboot,springDataJpa。研究一下目前可以正常运行,还没有出现什么bug。

一。配置文件中配置多数据源

spring:
  devtools:
    restart:
      enabled: false
  http:
    multipart:
      max-file-size: 1000Mb
      max-request-size: 1000Mb        
  # mysql DATABASE CONFIG
  datasource:
    name: dataSource
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    master:
        url: jdbc:mysql://127.0.0.1:3306/dataSource1?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&allowMultiQueries=true
        username: root
        password: 123456
        
    slave:
        url: jdbc:mysql://127.0.0.1:3306/dataSource2?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&allowMultiQueries=true
        username: root
        password: 123456
        

二。数据库连接池配置

连接池使用的阿里的DRUID,需要根据第一步配置的数据源生成主从配置。

/**
 * druid 配置多数据源
 *
 */
@Configuration
public class DruidConfig
{

    /**
     * 主DataSource 配置
     */
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.master")
    @Bean(name = "primaryDruidDataSource")
    public DataSource primaryDruidDataSource(Environment environment) {
        return DruidDataSourceBuilder.create().build(environment, "spring.datasource.master.");
    }


    /**
     * 从DataSource 配置
     */
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    @Bean(name = "slaveDruidDataSource")
    public DataSource slaveDruidDataSource(Environment environment) {
        return DruidDataSourceBuilder.create().build(environment, "spring.datasource.slave.");
    }

}
注:Environment是spring3.1提供的新的属性管理API.可以根据环境得到相应数据。

三。主从数据源的配置

数据源的配置采用注解的方式。

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryPrimary",
        transactionManagerRef = "transactionManagerPrimary",
        basePackages = {"com.test1.repository"},
        repositoryBaseClass = BaseSimpleRepository.class,
        repositoryFactoryBeanClass = RepositoryFactoryBean.class) //设置Repository所在位置
public class PrimaryConfig {

    @Resource(name = "primaryDruidDataSource")
    private DataSource primaryDruidDataSource;

    @Autowired
    private JpaProperties jpaProperties;

    @Primary
    @Bean(name = "entityManagerFactoryPrimary")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(primaryDruidDataSource)
                .properties(getVendorProperties(primaryDruidDataSource))
                .packages("com.test1.entity") //设置实体类所在位置
                .persistenceUnit("primaryPersistenceUnit")
                .build();
    }

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

    private Map<String, String> getVendorProperties(DataSource dataSource) {
        return jpaProperties.getHibernateProperties(dataSource);
    }

    @Primary
    @Bean(name = "transactionManagerPrimary")
    public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
    }

}

注:@Primary默认使用DataSource1为默认数据源。

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactorySlave",
        transactionManagerRef = "transactionManagerSlave",
        basePackages = {"com.test1.repository.test2"},
        repositoryBaseClass = BaseSimpleRepository.class,
        repositoryFactoryBeanClass = RepositoryFactoryBean.class) //设置Repository所在位置
public class SlaveConfig {

    @Resource(name = "slaveDruidDataSource")
    private DataSource slaveDruidDataSource;

    @Autowired
    private JpaProperties jpaProperties;

    @Bean(name = "entityManagerFactorySlave")
    public LocalContainerEntityManagerFactoryBean entityManagerFactorySlave(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean slavePersistenceUnit = builder
                .dataSource(slaveDruidDataSource)
                .properties(getVendorProperties(slaveDruidDataSource))
                .packages("com.test1.entity.test2") //设置实体类所在位置
                .persistenceUnit("slavePersistenceUnit")
                .build();
        slavePersistenceUnit.getJpaPropertyMap().remove("hibernate.hbm2ddl.auto");
        return slavePersistenceUnit;
    }

    @Bean(name = "entityManagerSlave")
    public EntityManager entityManagerSlave(EntityManagerFactoryBuilder builder) {
        return entityManagerFactorySlave(builder).getObject().createEntityManager();
    }

    private Map<String, String> getVendorProperties(DataSource dataSource) {
        return jpaProperties.getHibernateProperties(dataSource);
    }

    @Bean(name = "transactionManagerSlave")
    public PlatformTransactionManager transactionManagerSlave(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactorySlave(builder).getObject());
    }

}

这样就配置好了。如果是在旧项目中添加数据源,要把原来jpa的配置删除掉。

相关标签: 双数据源