springCloud+mybatisPlus+daynamicDatasource多数据源动态切换、分布式数据库事务、分表
在Spring Cloud环境下,结合Spring Cloud+MyBatis Plus+DynamicDataSource多数据源动态切换、分布式数据库事务,可以使用下面的示例代码来实现:
- 配置多数据源:
spring:
datasource:
dynamic:
primary: db1 # 设置主数据源
strict: false # 开启严格模式, 默认false不启用, 启用则未配置的数据源不允许使用
datasource:
db1:
url: jdbc:mysql://localhost:3306/db1
username: root
password:
driver-class-name: com.mysql.cj.jdbc.Driver
db2:
url: jdbc:mysql://localhost:3306/db2
username: root
password:
driver-class-name: com.mysql.cj.jdbc.Driver
- 配置DynamicDataSource:
@Configuration
@MapperScan(basePackages = "你的mapper包路径", sqlSessionFactoryRef = "sqlSessionFactory")
public class DynamicDataSourceConfig {
@Primary
@Bean
public DataSource dynamicDataSource(@Qualifier("db1") DataSource db1,
@Qualifier("db2") DataSource db2) {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
dynamicDataSource.setDefaultTargetDataSource(db1); // 设置默认数据源
Map<Object, Object> dataSourceMap = new HashMap<>();
dataSourceMap.put("db1", db1);
dataSourceMap.put("db2", db2);
dynamicDataSource.setTargetDataSources(dataSourceMap);
return dynamicDataSource;
}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dynamicDataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dynamicDataSource);
return sqlSessionFactoryBean.getObject();
}
}
- 动态数据源切换:
public class DynamicDataSourceContextHolder {
private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();
public static void setDataSource(String dataSource) {
CONTEXT_HOLDER.set(dataSource);
}
public static String getDataSource() {
return CONTEXT_HOLDER.get();
}
public static void clearDataSource() {
CONTEXT_HOLDER.remove();
}
}
在服务调用时,通过DynamicDataSourceContextHolder.setDataSource("数据源名")来切换数据源。
- 分布式事务管理:
确保你的Spring Cloud版本支持分布式事务,并且使用了如Rabbit
评论已关闭