1.实现原理(核心)
动态切换数据源(实现AbstractRoutingDataSource类基于本地副本动态切换数据源)
上述动态切换数据源时机,,最好的时机就是拦截mybatis的操作,写走主库读走从库 (此处要谈从库读性能,有兴趣可了解下clickhouse)
2.实现(此处着重描述动态数据源切换实现)
其他配置可参考 【shardingjdbc&Mysql】基于springboot+shardingjdbc+tkmapper实现mysql分库分表
DynamicDataSource.java
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import javax.sql.DataSource;
import java.util.Map;
public class DynamicDataSource extends AbstractRoutingDataSource {
public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
super.setDefaultTargetDataSource(defaultTargetDataSource);
super.setTargetDataSources(targetDataSources);
super.afterPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceContextHolder.getDataSourceType();
}
}
TmsDataSourceConfiguration.java
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class TmsDataSourceConfiguration {
@Bean(name = "tmsMasterDataSource")
@ConfigurationProperties(prefix = "spring.datasource.druid.tms.master")
@Primary
public DataSource tmsMasterDataSource(DruidProperties druidProperties) {
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean(name = "tmsSlaveDataSource")
@ConfigurationProperties(prefix = "spring.datasource.druid.tms.slave")
public DataSource tmsSlaveDataSource(DruidProperties druidProperties) {
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean(name = "tmsDynamicDataSource")
public DataSource tmsDynamicDataSource(@Qualifier("tmsMasterDataSource") DataSource tmsMasterDataSource,
@Qualifier("tmsSlaveDataSource") DataSource tmsSlaveDataSource) {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceTypeEnum.MASTER.name(), tmsMasterDataSource);
targetDataSources.put(DataSourceTypeEnum.SLAVE.name(), tmsSlaveDataSource);
return new DynamicDataSource(tmsMasterDataSource, targetDataSources);
}
}
3.实现效果
|