SpringBoot多数据源
目前最优的方式是,注入多个datasource 然后通过org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource在执行得时候设置根据key设置当前上下文不同的datasource,通过@Primary设置实现类为默认数据源。在事务中不支持数据源切换,因为事务默认不是分布式不跨库的。
下面这是为不同mapper设置不同datasource的方式,不优雅。
@Configuration
@MapperScan(basePackages = "com.activitytomongo.mapper", sqlSessionTemplateRef = "promoteSqlSessionTemplate")
public class PromoteDatasourceConfig {
@Bean(name = "promoteDatasource")
@ConfigurationProperties(prefix = "spring.datasource.promote")
public DataSource setPromoteDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "promoteTransactionManager")
public PlatformTransactionManager promoteSqlSessionTemplate(@Qualifier("promoteDatasource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "promoteSqlSessionFactory")
public SqlSessionFactory promoteSqlSessionFactory(@Qualifier("promoteDatasource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
}
@Bean(name = "promoteSqlSessionTemplate")
public SqlSessionTemplate setSqlSessionTemplate(
@Qualifier("promoteSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
// return new SqlSessionTemplate(sqlSessionFactory);
return new SqlSessionTemplate(sqlSessionFactory, ExecutorType.BATCH);
}
}