SpringBoot配置多个数据源

1、排除SpringBoot启动时对相关类的自动配置(也可以不排除,但是用不到的最好手动排除,保持良好的编程习惯),其中包括:

 DataSourceAutoConfiguration.class,
        DataSourceTransactionManagerAutoConfiguration.class,
        JdbcTemplateAutoConfiguration.class

具体方法:在@SpringBootApplication后面添加要exclude(排除)配置的类

@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class,
        DataSourceTransactionManagerAutoConfiguration.class,
        JdbcTemplateAutoConfiguration.class})

2、在配置文件中描述多个数据源的信息 ,本文使用内嵌的H2数据库进行演示,foo,bar只是用来区分两个不同数据源的字段,五固定含义

foo.datasource.url=jdbc:h2:mem:foo
foo.datasource.username=sa
foo.datasource.password=

bar.datasource.url=jdbc:h2:mem:bar
bar.datasource.username=sa
bar.datasource.password=

3、配置对应的DataSource数据源和PlatformTransactionManager事务管理

方法一:使用SpringBoot提供的DatasourceProperties

  @Bean
    @ConfigurationProperties("foo.datasource")
    public DataSourceProperties fooDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    public DataSource fooDataSource() {
        DataSourceProperties dataSourceProperties = fooDataSourceProperties();
        log.info("foo datasource: {}", dataSourceProperties.getUrl());
        return dataSourceProperties.initializeDataSourceBuilder().build();
    }

    @Bean
    @Resource
    public PlatformTransactionManager fooTxManager(DataSource fooDataSource) {
        return new DataSourceTransactionManager(fooDataSource);
    }

    @Bean
    @ConfigurationProperties("bar.datasource")
    public DataSourceProperties barDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    public DataSource barDataSource() {
        DataSourceProperties dataSourceProperties = barDataSourceProperties();
        log.info("bar datasource: {}", dataSourceProperties.getUrl());
        return dataSourceProperties.initializeDataSourceBuilder().build();
    }

    @Bean
    @Resource
    public PlatformTransactionManager barTxManager(DataSource barDataSource) {
        return new DataSourceTransactionManager(barDataSource);
    }

方法二:使用Abstractroutingdatasource配置多个数据源

https://www.jianshu.com/p/b158476dd33c

3、使用多数据源

在dao层中,根据自己需要,引用对应的数据源

@Autowired
DataSource fooDataSource
@Autowired
DataSource barDataSource
或者
@Autowired
private JdbcTemplate fooJdbcTemplate;
@Autowired
private JdbcTemplate barJdbcTemplate;

 

你可能感兴趣的:(SpringBoot学习记录)