Java實現(xiàn)多數(shù)據(jù)源的幾種方式總結(jié)
一、利用Spring提供的類實現(xiàn)
1)在yml文件當(dāng)中配置多數(shù)據(jù)源
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=false
username: root
password: root
initial-size: 1
min-idle: 1
max-active: 20
test-on-borrow: true
driver-class-name: com.mysql.cj.jdbc.Driver
datasource2:
url: jdbc:mysql://127.0.0.1:3306/datasource2?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&useSSL=false
username: root
password: root
initial-size: 1
min-idle: 1
max-active: 20
test-on-borrow: true
driver-class-name: com.mysql.cj.jdbc.Driver2) 定義一個DataSourceConfig 配置類來配置兩個數(shù)據(jù)源
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.datasource1")
public DataSource dataSource1() {
// 底層會自動拿到spring.datasource中的配置, 創(chuàng)建一個DruidDataSource
return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.datasource2")
public DataSource dataSource2() {
// 底層會自動拿到spring.datasource中的配置, 創(chuàng)建一個DruidDataSource
return DruidDataSourceBuilder.create().build();
}
/* @Bean
public Interceptor dynamicDataSourcePlugin(){
return new DynamicDataSourcePlugin();
}
*/
@Bean
public DataSourceTransactionManager transactionManager1(DynamicDataSource dataSource){
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
@Bean
public DataSourceTransactionManager transactionManager2(DynamicDataSource dataSource){
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
}3)自定義一個類 來 繼承 org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
** 在類里面注入分別注入兩個數(shù)據(jù)源**
// 寫
@Autowired
DataSource dataSource1;
// 讀
@Autowired
DataSource dataSource2;
// 返回當(dāng)前數(shù)據(jù)源標(biāo)識
@Override
protected Object determineCurrentLookupKey() {
return name.get();
}** 在這個類初始化完成之后,進行數(shù)據(jù)源的注入**
// 當(dāng)前使用的數(shù)據(jù)源標(biāo)識
public static ThreadLocal<String> name=new ThreadLocal<>();
@Override
public void afterPropertiesSet() {
// 為targetDataSources初始化所有數(shù)據(jù)源
Map<Object, Object> targetDataSources=new HashMap<>();
targetDataSources.put("W",dataSource1);
targetDataSources.put("R",dataSource2);
super.setTargetDataSources(targetDataSources);
// 為defaultTargetDataSource 設(shè)置默認(rèn)的數(shù)據(jù)源
super.setDefaultTargetDataSource(dataSource1);
super.afterPropertiesSet();
}**在service中使用指定的數(shù)據(jù)源 **
@Service
public class FriendImplService implements FriendService {
@Autowired
FriendMapper friendMapper;
@Override
@WR("R") // 庫2
public List<Friend> list() {
// DynamicDataSource.name.set("R");
return friendMapper.list();
}
@Override
@WR("W") // 庫1
public void save(Friend friend) {
// DynamicDataSource.name.set("W");
friendMapper.save(friend);
}
}上面采用注解的方式就是,其實是利用切面進行數(shù)據(jù)源的設(shè)置,和注釋的注釋方式類似
二、利用mybatis層次實現(xiàn)
1)分別配置兩個配置源,單獨配置
** 編寫WMyBatisConfig配置文件**
@Configuration
// 繼承mybatis:
// 1. 指定掃描的mapper接口包(主庫)
// 2. 指定使用sqlSessionFactory是哪個(主庫)
@MapperScan(basePackages = "com.datasource.dynamic.mybatis.mapper.w",
sqlSessionFactoryRef="wSqlSessionFactory")
public class WMyBatisConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.datasource1")
public DataSource dataSource1() {
// 底層會自動拿到spring.datasource中的配置, 創(chuàng)建一個DruidDataSource
return DruidDataSourceBuilder.create().build();
}
@Bean
@Primary
public SqlSessionFactory wSqlSessionFactory()
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
// 指定主庫
sessionFactory.setDataSource(dataSource1());
// 指定主庫對應(yīng)的mapper.xml文件
/*sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/order/*.xml"));*/
return sessionFactory.getObject();
}
@Bean
@Primary
public DataSourceTransactionManager wTransactionManager(){
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource1());
return dataSourceTransactionManager;
}
@Bean
public TransactionTemplate wTransactionTemplate(){
return new TransactionTemplate(wTransactionManager());
}
}** 編寫RMyBatisConfig 配置文件**
@Configuration
// 繼承mybatis:
// 1. 指定掃描的mapper接口包(主庫)
// 2. 指定使用sqlSessionFactory是哪個(主庫)
@MapperScan(basePackages = "com.tuling.datasource.dynamic.mybatis.mapper.w",
sqlSessionFactoryRef="wSqlSessionFactory")
public class WMyBatisConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.datasource1")
public DataSource dataSource1() {
// 底層會自動拿到spring.datasource中的配置, 創(chuàng)建一個DruidDataSource
return DruidDataSourceBuilder.create().build();
}
@Bean
@Primary
public SqlSessionFactory wSqlSessionFactory()
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
// 指定主庫
sessionFactory.setDataSource(dataSource1());
// 指定主庫對應(yīng)的mapper.xml文件
/*sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/order/*.xml"));*/
return sessionFactory.getObject();
}
@Bean
@Primary
public DataSourceTransactionManager wTransactionManager(){
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource1());
return dataSourceTransactionManager;
}
@Bean
public TransactionTemplate wTransactionTemplate(){
return new TransactionTemplate(wTransactionManager());
}
}2) 在serviceImpl實現(xiàn)層 單獨調(diào)用配置的Mapper代理類
@Autowired
private RFriendMapper rFriendMapper;
@Autowired
private WFriendMapper wFriendMapper;
// 讀-- 讀庫
@Override
public List<Friend> list() {
return rFriendMapper.list();
}
// 保存-- 寫庫
@Override
public void saveW(Friend friend) {
friend.setName("loulan");
wFriendMapper.save(friend);
}
// 保存-- 讀庫
@Override
public void saveR(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實現(xiàn)==
@Service
public class FriendImplService implements FriendService {
@Autowired
FriendMapper friendMapper;
@Override
@DS("slave_1") // 從庫, 如果按照下劃線命名方式配置多個 , 可以指定前綴即可(組名)
public List<Friend> list() {
return friendMapper.list();
}
@Override
@DS("master")
public void save(Friend friend) {
friendMapper.save(friend);
}
@DS("master")
@DSTransactional
public void saveAll(){
// 執(zhí)行多數(shù)據(jù)源的操作
}
}總結(jié)
到此這篇關(guān)于Java實現(xiàn)多數(shù)據(jù)源的幾種方式的文章就介紹到這了,更多相關(guān)Java實現(xiàn)多數(shù)據(jù)源內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java8?Stream大數(shù)據(jù)量List分批處理切割方式
這篇文章主要介紹了java8?Stream大數(shù)據(jù)量List分批處理切割方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
常用數(shù)字簽名算法RSA與DSA的Java程序內(nèi)實現(xiàn)示例
這篇文章主要介紹了常用數(shù)字簽名算法RSA與DSA的Java程序內(nèi)實現(xiàn)示例,一般來說DSA算法用于簽名的效率會比RSA要快,需要的朋友可以參考下2016-04-04
Java面試題-實現(xiàn)復(fù)雜鏈表的復(fù)制代碼分享
這篇文章主要介紹了Java面試題-實現(xiàn)復(fù)雜鏈表的復(fù)制代碼分享,小編覺得還是挺不錯的,具有參考價值,需要的朋友可以了解下。2017-10-10
詳解mybatis foreach collection示例
這篇文章主要介紹了詳解mybatis foreach collection的相關(guān)資料,需要的朋友可以參考下2017-10-10

