springboot多数据源配置
因项目需要实现一个同步数据表的功能,即从一个数据库的一张表中查询数据,然后将数据插入到另一个数据库的一张表中
1.首先在application.properties文件中配置两个数据库的连接信息
1 #NIV2587W DataSource Configuration 2 spring.datasource.first.driver-class-name=oracle.jdbc.driver.OracleDriver 3 spring.datasource.first.jdbc-url= 4 spring.datasource.first.username= 5 spring.datasource.first.password= 6 7 #rbccpack DataSource Configuration 8 spring.datasource.second.driver-class-name=oracle.jdbc.driver.OracleDriver 9 spring.datasource.second.jdbc-url= 10 spring.datasource.second.username= 11 spring.datasource.second.password=
其中Oracle连接的url有三种写法,可参考https://blog.csdn.net/gnail_oug/article/details/80075263
2.创建配置类,以一个为例
@Configuration @MapperScan(basePackages = {"com.dao.niv257w"}, sqlSessionTemplateRef = "NIV257WSqlSessionTemplate") public class NIV257WDataSourceConfig { @Bean(name = "NIV257WDataSource") @ConfigurationProperties(prefix = "spring.datasource.first") public DataSource NIV257WDataSource() { return DataSourceBuilder.create().build(); } @Bean public SqlSessionFactory NIV257WSqlSessionFactory(@Qualifier("NIV257WDataSource") DataSource dataSource) { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); try { bean.setMapperLocations(resolver.getResources("classpath*:mapper/niv257w/*.xml")); return bean.getObject(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } @Bean public SqlSessionTemplate NIV257WSqlSessionTemplate(@Qualifier("NIV257WSqlSessionFactory") SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } @Bean public PlatformTransactionManager NIV257WTransactionManager(@Qualifier("NIV257WDataSource")DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } }
创建好两个配置类之后,即完成了对两个数据源的配置,且支持利用注解来进行事务管理
1 @Override 2 @Transactional("RBCCPACKTransactionManager") 3 public void synchronizePlannedOrder() {
只需用注解指明用到的是哪一个PlatformTransactionManager,即可对方法进行最基本的事务控制
欢迎指正交流!