获取mybatis-plus-dynamic-datasource中的多数据源实例
时间: 2024-01-07 18:04:51 浏览: 155
基于mybatis-plus实现多租户级别的数据隔离
在 mybatis-plus-dynamic-datasource 中获取多数据源实例的方法如下:
1. 导入相关依赖:
```xml
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>2.5.3</version>
</dependency>
```
2. 在 application.yml 或 application.properties 中配置数据源信息,例如:
```yaml
spring:
datasource:
dynamic:
primary: ds1 # 设置默认数据源
datasource:
ds1:
url: jdbc:mysql://localhost:3306/db1
username: root
password: 123456
ds2:
url: jdbc:mysql://localhost:3306/db2
username: root
password: 123456
```
3. 创建一个继承自 AbstractRoutingDataSource 的类,用于动态切换数据源:
```java
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceContextHolder.getDataSourceKey();
}
}
```
4. 创建一个数据源上下文持有者类,用于设置和获取当前线程使用的数据源:
```java
public class DynamicDataSourceContextHolder {
private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();
public static void setDataSourceKey(String dataSourceKey) {
CONTEXT_HOLDER.set(dataSourceKey);
}
public static String getDataSourceKey() {
return CONTEXT_HOLDER.get();
}
public static void clearDataSourceKey() {
CONTEXT_HOLDER.remove();
}
}
```
5. 配置数据源切换策略和数据源 bean:
```java
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.dynamic")
public DataSourceProperties dataSourceProperties() {
return new DataSourceProperties();
}
@Bean
public DataSource dataSource(DataSourceProperties properties) {
Map<String, DataSource> dataSourceMap = new HashMap<>();
dataSourceMap.put("ds1", properties.getDataSource("ds1"));
dataSourceMap.put("ds2", properties.getDataSource("ds2"));
// 设置默认数据源
DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource();
dataSource.setDefaultTargetDataSource(dataSourceMap.get(properties.getPrimary()));
dataSource.setTargetDataSources(dataSourceMap);
return dataSource;
}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
MybatisSqlSessionFactoryBean sessionFactoryBean = new MybatisSqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
return sessionFactoryBean.getObject();
}
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
```
现在,你可以通过注入 DataSource 类型的 bean 来获取多数据源实例,例如:
```java
@Autowired
private DataSource dataSource;
```
然后,你就可以使用这个数据源实例来执行数据库操作了。
阅读全文