Java实现多数据源的方式
文章目录
一、利用Spring提供的类实现
1)在yml文件当中配置多数据源
spring:datasource:type: com.alibaba.druid.pool.DruidDataSource
datasource1:url: jdbc:mysql://127.0.0.1:3306/datasource1?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&useSSL=falseusername: root
password: root
initial-size:1min-idle:1max-active:20test-on-borrow:truedriver-class-name: com.mysql.cj.jdbc.Driver
datasource2:url: jdbc:mysql://127.0.0.1:3306/datasource2?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&useSSL=falseusername: root
password: root
initial-size:1min-idle:1max-active:20test-on-borrow:truedriver-class-name: com.mysql.cj.jdbc.Driver
2) 定义一个DataSourceConfig 配置类来配置两个数据源
@ConfigurationpublicclassDataSourceConfig{@Bean@ConfigurationProperties(prefix ="spring.datasource.datasource1")publicDataSourcedataSource1(){// 底层会自动拿到spring.datasource中的配置, 创建一个DruidDataSourcereturnDruidDataSourceBuilder.create().build();}@Bean@ConfigurationProperties(prefix ="spring.datasource.datasource2")publicDataSourcedataSource2(){// 底层会自动拿到spring.datasource中的配置, 创建一个DruidDataSourcereturnDruidDataSourceBuilder.create().build();}/* @Bean
public Interceptor dynamicDataSourcePlugin(){
return new DynamicDataSourcePlugin();
}
*/@BeanpublicDataSourceTransactionManagertransactionManager1(DynamicDataSource dataSource){DataSourceTransactionManager dataSourceTransactionManager =newDataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);return dataSourceTransactionManager;}@BeanpublicDataSourceTransactionManagertransactionManager2(DynamicDataSource dataSource){DataSourceTransactionManager dataSourceTransactionManager =newDataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);return dataSourceTransactionManager;}}
3)自定义一个类 来 继承 org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
** 在类里面注入分别注入两个数据源**
// 写@AutowiredDataSource dataSource1;// 读@AutowiredDataSource dataSource2;// 返回当前数据源标识@OverrideprotectedObjectdetermineCurrentLookupKey(){return name.get();}
** 在这个类初始化完成之后,进行数据源的注入**
// 当前使用的数据源标识publicstaticThreadLocal<String> name=newThreadLocal<>();@OverridepublicvoidafterPropertiesSet(){// 为targetDataSources初始化所有数据源Map<Object,Object> targetDataSources=newHashMap<>();
targetDataSources.put("W",dataSource1);
targetDataSources.put("R",dataSource2);super.setTargetDataSources(targetDataSources);// 为defaultTargetDataSource 设置默认的数据源super.setDefaultTargetDataSource(dataSource1);super.afterPropertiesSet();}
**在service中使用指定的数据源 **
@ServicepublicclassFriendImplServiceimplementsFriendService{@AutowiredFriendMapper friendMapper;@Override@WR("R")// 库2publicList<Friend>list(){// DynamicDataSource.name.set("R");return friendMapper.list();}@Override@WR("W")// 库1publicvoidsave(Friend friend){// DynamicDataSource.name.set("W");
friendMapper.save(friend);}}
上面采用注解的方式就是,其实是利用切面进行数据源的设置,和注释的注释方式类似
二、利用mybatis层次实现
1)分别配置两个配置源,单独配置
** 编写WMyBatisConfig配置文件**
@Configuration// 继承mybatis:// 1. 指定扫描的mapper接口包(主库)// 2. 指定使用sqlSessionFactory是哪个(主库)@MapperScan(basePackages ="com.datasource.dynamic.mybatis.mapper.w",
sqlSessionFactoryRef="wSqlSessionFactory")publicclassWMyBatisConfig{@Bean@ConfigurationProperties(prefix ="spring.datasource.datasource1")publicDataSourcedataSource1(){// 底层会自动拿到spring.datasource中的配置, 创建一个DruidDataSourcereturnDruidDataSourceBuilder.create().build();}@Bean@PrimarypublicSqlSessionFactorywSqlSessionFactory()throwsException{finalSqlSessionFactoryBean sessionFactory =newSqlSessionFactoryBean();// 指定主库
sessionFactory.setDataSource(dataSource1());// 指定主库对应的mapper.xml文件/*sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/order/*.xml"));*/return sessionFactory.getObject();}@Bean@PrimarypublicDataSourceTransactionManagerwTransactionManager(){DataSourceTransactionManager dataSourceTransactionManager =newDataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource1());return dataSourceTransactionManager;}@BeanpublicTransactionTemplatewTransactionTemplate(){returnnewTransactionTemplate(wTransactionManager());}}
** 编写RMyBatisConfig 配置文件**
@Configuration// 继承mybatis:// 1. 指定扫描的mapper接口包(主库)// 2. 指定使用sqlSessionFactory是哪个(主库)@MapperScan(basePackages ="com.tuling.datasource.dynamic.mybatis.mapper.w",
sqlSessionFactoryRef="wSqlSessionFactory")publicclassWMyBatisConfig{@Bean@ConfigurationProperties(prefix ="spring.datasource.datasource1")publicDataSourcedataSource1(){// 底层会自动拿到spring.datasource中的配置, 创建一个DruidDataSourcereturnDruidDataSourceBuilder.create().build();}@Bean@PrimarypublicSqlSessionFactorywSqlSessionFactory()throwsException{finalSqlSessionFactoryBean sessionFactory =newSqlSessionFactoryBean();// 指定主库
sessionFactory.setDataSource(dataSource1());// 指定主库对应的mapper.xml文件/*sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/order/*.xml"));*/return sessionFactory.getObject();}@Bean@PrimarypublicDataSourceTransactionManagerwTransactionManager(){DataSourceTransactionManager dataSourceTransactionManager =newDataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource1());return dataSourceTransactionManager;}@BeanpublicTransactionTemplatewTransactionTemplate(){returnnewTransactionTemplate(wTransactionManager());}}
2) 在serviceImpl实现层 单独调用配置的Mapper代理类
@AutowiredprivateRFriendMapper rFriendMapper;@AutowiredprivateWFriendMapper wFriendMapper;// 读-- 读库@OverridepublicList<Friend>list(){return rFriendMapper.list();}// 保存-- 写库@OverridepublicvoidsaveW(Friend friend){
friend.setName("loulan");
wFriendMapper.save(friend);}// 保存-- 读库@OverridepublicvoidsaveR(Friend friend){
friend.setName("loulan");
rFriendMapper.save(friend);}
三、Spring自动化支持
1) 引入pom依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>
2)在service层利用注解==@DS实现==
@ServicepublicclassFriendImplServiceimplementsFriendService{@AutowiredFriendMapper friendMapper;@Override@DS("slave_1")// 从库, 如果按照下划线命名方式配置多个 , 可以指定前缀即可(组名)publicList<Friend>list(){return friendMapper.list();}@Override@DS("master")publicvoidsave(Friend friend){
friendMapper.save(friend);}@DS("master")@DSTransactionalpublicvoidsaveAll(){// 执行多数据源的操作}}
版权归原作者 -半度 所有, 如有侵权,请联系我们删除。