Spring Boot系列(三):多数据源配置

简介

在某些场合总会用到多个数据源的情况,今天记录下来,方便“日”后好用。

公共配置

yml的配置和Datasource的配置是JdbcTemplate和Spring Data Jpa共有的代码:

yml:

spring:
  datasource:
    zxc:
      driver-class-name: com.mysql.jdbc.Driver
      username: root
      password: root
      url: jdbc:mysql://localhost:3306/springboot?characterEncoding=utf-8&useSSL=false
    test:
      driver-class-name: com.mysql.jdbc.Driver
      username: root
      password: root
      url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: update

配置类:

/**
 * 创建数据源
 *
 * @author: uncle
 * @apdateTime: 2018-01-09 20:52
 */
@Configuration
public class DataSourceConfig {

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

    @Bean(name = "testDataSource")
    @Qualifier(value = "testDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test")
    /**
     * Indicates that a bean should be given preference when multiple candidates are qualified to
     * autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates,
     * it will be the autowired value.
     *
     * 如果有多个候选对象时,被此注解标记的对象将称为默认值,此Bean也将是”主“的身份.
     */
    @Primary
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }
}

JdbcTemplate 多数据源

只需要在创建JdbcTemplate的声明好是使用哪个数据源就行,比较简单:

@Bean(name = "zxcJdbcTemplate")
public JdbcTemplate zxcDataSource(@Qualifier("zxcDataSource") DataSource dataSource) {
    return new JdbcTemplate(dataSource);
}
@Bean(name = "testJdbcTemplate")
public JdbcTemplate testDataSource(@Qualifier("testDataSource")DataSource dataSource) {
    return new JdbcTemplate(dataSource);
}

然后在程序中使用即可:

@Autowired
@Qualifier("zxcJdbcTemplate")
protected JdbcTemplate jdbcTemplate1;

@Autowired
@Qualifier("testJdbcTemplate")
protected JdbcTemplate jdbcTemplate2;

Spring Data Jpa 多数据源

这个比JdbcTemplate就复杂不少。先准备前提条件pojo + dao,此处省略。只看其中的一个数据源的配置类:

/**
 * 关联数据源 + 配置文件(通过数据源进行关联) + Dao + Pojo
 * 
 * @author: uncle
 * @apdateTime: 2018-01-09 21:23
 */
@Configuration
// 开启事务支持
@EnableTransactionManagement
// http://blog.csdn.net/u013473691/article/details/52351830,开启对Spring Data JPA Repostory的支持。
@EnableJpaRepositories(
        /* dao类位置千万别指定错误 */
        basePackages = {"com.zengxiaochen.dao"},
        entityManagerFactoryRef = "entityManagerFactoryTest",
        transactionManagerRef = "transactionManagerTest"
)
public class TestConfig {
    /**
     * 绑定数据源
     */
    @Autowired
    @Qualifier("testDataSource")
    private DataSource testDataSource;

    /**
     * Jpa的配置参数管理类
     */
    @Autowired
    private JpaProperties jpaProperties;

    // EntityManager API用于创建和删除持久化实体实例,通过它们的主键查找实体,并查询实体。
    @Primary
    @Bean("entityManagerTest")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        // 通过工厂创建
        return entityManagerFactoryTest(builder).getObject().createEntityManager();
    }

    @Primary
    @Bean("entityManagerFactoryTest")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryTest(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(testDataSource)
                .properties(getProperties(testDataSource))
                // 绑定实体类
                .packages("com.zengxiaochen.pojo")
                // 设置 EntityManagerFactory 的名字,单数据源时可忽略
                .persistenceUnit("testPersistenceUnit")
                .build();
    }

    /**
     * 设置配置文件,获取对主Hibernate EntityManagerFactory初始化的配置属性。
     *
     * @param dataSource
     * @return
     */
    public Map<String, String> getProperties(DataSource dataSource) {
        return jpaProperties.getHibernateProperties(dataSource);
    }

    /**
     * 事务管理
     *
     * @param builder
     * @return
     */
    @Primary
    @Bean("transactionManagerTest")
    public PlatformTransactionManager transactionManagerZxg(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryZxg(builder).getObject());
    }
}

这些弄好之后进行测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class DataSourceTest {

    @Autowired
    private TestDao testDao;

    @Test
    public void test1() {
        testDao.save(new Zxc("111"));
    }
}
Last modification:January 10th, 2018 at 06:17 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment