一.项目基本结构
二.详细内容
1.项目配置文件(yml):
ps:springboot使用的是1.5.9版本,若使用2.x.x版本,项目地址:server:servlet:context-path: /xxxx
2.配置文件包(config)
2.1 MybatisPlusConfig:配置mybatis相关数据(也可在yml中配置),启动加载多个数据源;
@EnableTransactionManagement
@Configuration
@MapperScan("com.hy.testtwo.**.mapper.db*")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
paginationInterceptor.setLocalPage(true);
return paginationInterceptor;
}
/**
* 路径为配置文件中数据源路径
* @return
*/
@Bean(name = "db1")
@ConfigurationProperties(prefix = "spring.datasource.druid.db1")
public DataSource db1() {
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "db2")
@ConfigurationProperties(prefix = "spring.datasource.druid.db2")
public DataSource db2() {
return DruidDataSourceBuilder.create().build();
}
/**
* 动态数据源配置
*
* @return
*/
@Bean
@Primary
public DataSource multipleDataSource(@Qualifier("db1") DataSource db1,
@Qualifier("db2") DataSource db2) {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DBTypeEnum.db1.getValue(), db1);
targetDataSources.put(DBTypeEnum.db2.getValue(), db2);
dynamicDataSource.setTargetDataSources(targetDataSources);
dynamicDataSource.setDefaultTargetDataSource(db2);
return dynamicDataSource;
}
@Bean("sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(multipleDataSource(db1(), db2()));
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setJdbcTypeForNull(JdbcType.NULL);
configuration.setMapUnderscoreToCamelCase(true);
configuration.setCacheEnabled(false);
sqlSessionFactory.setConfiguration(configuration);
//PerformanceInterceptor(),OptimisticLockerInterceptor()
//添加分页功能
sqlSessionFactory.setPlugins(new Interceptor[]{
paginationInterceptor()
});
// sqlSessionFactory.setGlobalConfig(globalConfiguration());
return sqlSessionFactory.getObject();
}
2.2 DymamicDataSource:动态数据源决策
@Slf4j
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
log.info("获取数据源");
return DbContextHolder.getDbType();
}
}
2.3 DataSourceSwitchAspect: Aop实现数据源切换
@Aspect
@Order(value = -100)
@Component
@Slf4j
public class DataSourceSwitchAspect {
@Pointcut("execution(* com.hy.testtwo.mapper.db1..*.*(..))")
private void db1Aspect() {
log.info("db1");
}
@Pointcut("execution(* com.hy.testtwo.mapper.db2..*.*(..))")
private void db2Aspect() {
log.info("db2");
}
@Before("db1Aspect()")
public void db1() {
log.info("切换到db1 数据源...");
DbContextHolder.setDbType(DBTypeEnum.db1);
}
@Before("db2Aspect()")
public void db2() {
log.info("切换到db2 数据源...");
DbContextHolder.setDbType(DBTypeEnum.db2);
}
}
2.4 DbContextHolder:设置获取数据源
public class DbContextHolder {
private static final ThreadLocal contextHolder = new ThreadLocal<>();
/**
* 设置数据源
* @param dbTypeEnum
*/
public static void setDbType(DBTypeEnum dbTypeEnum) {
contextHolder.set(dbTypeEnum.getValue());
}
/**
* 取得当前数据源
* @return
*/
public static String getDbType() {
return (String) contextHolder.get();
}
/**
* 清除上下文数据
*/
public static void clearDbType() {
contextHolder.remove();
}
}
3.逻辑代码
此项目为开发方便,使用jpa,lombok,swagger等工具,dao层,controller层详细代码此处略过;service层仅贴出实现类部分代码:
@Resource
private TestRecordInfoMapper infoMapper;
@Resource
private TestRecordMemoryMapper memoryMapper;
@Override
public BaseRespVo<TestRecordInfoEntity> queryById(Integer id) {
// Optional<TestRecordInfoEntity> entity = infoMapper.findById(id);
// if (!entity.isPresent()){
// return BaseRespVo.error(IError.DATA_NOT_EXIST);
// }
// return BaseRespVo.success(entity.get());
TestRecordInfoEntity entity = infoMapper.findOne(id);
return BaseRespVo.success(entity);
}
@Override
public BaseRespVo<TestRecordMemoryEntity> queryByIdForMeory(Integer id) {
TestRecordMemoryEntity entity = memoryMapper.findOne(id);
return BaseRespVo.success(entity);
}
ps:注解部分为spring2.0以上版本jpa查询相关代码
三 gitee地址:
https://gitee.com/HuangyinGl/hytests.git