MybatisPlus 配置多数据源
在MyBatis Plus中配置多数据源通常涉及以下几个步骤:
- 配置数据源信息。
- 配置SqlSessionFactory和Mapper接口。
- 使用AbstractRoutingDataSource实现动态数据源的路由。
以下是一个简化的示例代码:
// 配置数据源
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
// 配置动态数据源
@Bean
public DynamicDataSource dynamicDataSource() {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
dynamicDataSource.setDefaultTargetDataSource(primaryDataSource());
Map<Object, Object> dataSourceMap = new HashMap<>();
dataSourceMap.put("primary", primaryDataSource());
dataSourceMap.put("secondary", secondaryDataSource());
dynamicDataSource.setTargetDataSources(dataSourceMap);
return dynamicDataSource;
}
// 配置SqlSessionFactory
@Bean
public SqlSessionFactory sqlSessionFactory(DynamicDataSource dynamicDataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dynamicDataSource);
return sqlSessionFactoryBean.getObject();
}
}
// 动态数据源
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getCurrentDataSource();
}
}
// 数据源上下文持有者
public class DataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
public static void setCurrentDataSource(String dataSourceType) {
contextHolder.set(dataSourceType);
}
public static String getCurrentDataSource() {
return contextHolder.get();
}
public static void clearDataSource() {
contextHolder.remove();
}
}
// 使用动态数据源
public class DataSourceRouting {
public void usePrimaryDataSource() {
DataSourceContextHolder.setCurrentDataSource("primary");
// 执行操作
DataSourceContextHolder.clearDataSource();
}
public void useSecondaryDataSource() {
DataSourceContextHolder.
评论已关闭