一、背景以及為什么需要學習
在高并發的項目中,單數據庫已無法承載大數據量的訪問,因此需要使用多個數據庫進行對數據的讀寫分離,此外就是在微服化的今天,我們在項目中可能采用各種不同存儲,因此也需要連接不同的數據庫,居于這樣的背景,這里簡單分享實現的思路以及實現方案
二、實現方式
多數據源實現思路有兩種,一種是通過配置多個SqlSessionFactory實現多數據源;
1、通過配置多個SqlSessionFactory實現多數據源
2、通過Spring提供的AbstractRoutingDataSource抽象了一個DynamicDataSource實現動態切換數據源
三、方式一:不同庫的Mapper指定不同的SqlSessionFactory
1 針對不同的庫分別放置對用不同的SqlSessionFactory
UserDataSourceConfiguration
@Configuration
@MapperScan(basePackages = "org.datasource.demo1.usermapper",sqlSessionFactoryRef = "userSqlSessionFactory")
public class UserDataSourceConfiguration {public static final String MAPPER_LOCATION = "classpath:usermapper/*.xml";@Primary@Bean("userDataSource")@ConfigurationProperties(prefix = "spring.datasource.user")public DataSource userDataSource() {return DataSourceBuilder.create().build();}@Bean(name = "userTransactionManager")@Primarypublic PlatformTransactionManager userTransactionManager(@Qualifier("userDataSource") DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}@Primary@Bean(name = "userSqlSessionFactory")public SqlSessionFactory userSqlSessionFactory(@Qualifier("userDataSource") DataSource dataSource) throws Exception {final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();sessionFactoryBean.setDataSource(dataSource);sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(UserDataSourceConfiguration.MAPPER_LOCATION));return sessionFactoryBean.getObject();}}
SoulDataSourceConfiguration
@Configuration
@MapperScan(basePackages = "org.datasource.demo1.soulmapper",sqlSessionFactoryRef = "soulSqlSessionFactory")
public class SoulDataSourceConfiguration {public static final String MAPPER_LOCATION = "classpath:soulmapper/*.xml";@Bean("soulDataSource")@ConfigurationProperties(prefix = "spring.datasource.soul")public DataSource soulDataSource() {return DataSourceBuilder.create().build();}@Bean(name = "soulTransactionManager")public PlatformTransactionManager soulTransactionManager(@Qualifier("soulDataSource") DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}@Bean(name = "soulSqlSessionFactory")public SqlSessionFactory soulSqlSessionFactory(@Qualifier("soulDataSource") DataSource dataSource) throws Exception {final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();sessionFactoryBean.setDataSource(dataSource);sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(SoulDataSourceConfiguration.MAPPER_LOCATION));return sessionFactoryBean.getObject();}}
2 使用和測試
@Service
public class AppAuthService {@Autowiredprivate AppAuthMapper appAuthMapper;@Transactional(rollbackFor = Exception.class)public int getCount() {int a = appAuthMapper.listCount();int b = 1 / 0;return a;}}@SpringBootTest
@RunWith(SpringRunner.class)
public class TestDataSource {@Autowiredprivate AppAuthService appAuthService;@Autowiredprivate SysUserService sysUserService;@Testpublic void test_dataSource1(){int b=sysUserService.getCount();int a=appAuthService.getCount();}
}
3 總結
此種方式使用起來分層明確,不存在任何冗余代碼,不足地方就是每個庫都需要對應一個配置類,該配置類中實現方式都基本類似,該種解決方案每個配置類中都存在事務管理器,因此不需要單獨再去額外的關注。在使用時需要指定事務管理器
四、AOP+自定義注解
關于采用Spring AOP方式實現原理就是把多個數據源存儲在一個 Map中,當需要使用某個數據源時,從 Map中獲取此數據源進行處理。
1 AbstractRoutingDataSource
在Spring中提供了AbstractRoutingDataSource來實現此功能,繼承AbstractRoutingDataSource類并覆寫其determineCurrentLookupKey()方法就可以完成數據源切換,該方法只需要返回數據源key即可,也就是存放數據源的Map的key,接下來我們來看一下AbstractRoutingDataSource整體的繼承結構,看他是如何做到的。
在整體的繼承結構上我們會發現AbstractRoutingDataSource最終是繼承于DataSource,因此當我們繼承AbstractRoutingDataSource是我們自身也是一個數據源,對于數據源必然有連接數據庫的動作,如下代碼:
public Connection getConnection() throws SQLException {return this.determineTargetDataSource().getConnection();
}public Connection getConnection(String username, String password) throws SQLException {return this.determineTargetDataSource().getConnection(username, password);
}
只是AbstractRoutingDataSource的getConnection()方法里實際是調用determineTargetDataSource()返回的數據源的getConnection()方法。
protected DataSource determineTargetDataSource() {Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");Object lookupKey = this.determineCurrentLookupKey();DataSource dataSource = (DataSource)this.resolvedDataSources.get(lookupKey);if (dataSource == null && (this.lenientFallback || lookupKey == null)) {dataSource = this.resolvedDefaultDataSource;}if (dataSource == null) {throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");} else {return dataSource;}
}
該方法通過determineCurrentLookupKey()方法獲取一個key,通過key從resolvedDataSources中獲取數據源DataSource對象。determineCurrentLookupKey()是個抽象方法,需要繼承AbstractRoutingDataSource的類實現;而resolvedDataSources是一個Map<Object, DataSource>,里面應該保存當前所有可切換的數據源。