若依ruoyi 动态多数据源配置(多种不同类型的数据库mysql,oracle,sqlite3,sqlserver等等)
在RuoYi中配置多数据源,首先需要定义多个数据源的配置信息,然后通过配置文件指定默认数据源,最后在代码中动态切换数据源。以下是一个简化的示例:
- 在
application.yml
中配置多个数据源:
spring:
datasource:
dynamic:
primary: mysql # 设置默认数据源
datasource:
mysql:
url: jdbc:mysql://localhost:3306/your_mysql_db
username: your_mysql_username
password: your_mysql_password
driver-class-name: com.mysql.cj.jdbc.Driver
oracle:
url: jdbc:oracle:thin:@localhost:1521:your_oracle_db
username: your_oracle_username
password: your_oracle_password
driver-class-name: oracle.jdbc.OracleDriver
sqlite3:
url: jdbc:sqlite:your_sqlite3_db_path
driver-class-name: org.sqlite.JDBC
# sqlite不需要用户名和密码
sqlserver:
url: jdbc:sqlserver://localhost:1433;databaseName=your_sqlserver_db
username: your_sqlserver_username
password: your_sqlserver_password
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
- 创建
DataSourceConfig
类,用于配置多数据源:
@Configuration
@MapperScan(basePackages = "com.yourpackage.mapper.dynamic", sqlSessionFactoryRef = "dynamicSqlSessionFactory")
public class DataSourceConfig {
@Primary
@Bean
public DataSource dynamicDataSource(@Value("${spring.datasource.dynamic.primary}") String primary) {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
// 配置多个数据源
Map<Object, Object> targetDataSources = new HashMap<>();
// 这里添加其他数据源配置
// ...
dynamicDataSource.setTargetDataSources(targetDataSources);
// 设置默认数据源
dynamicDataSource.setDefaultTargetDataSource(primary);
return dynamicDataSource;
}
@Bean
public SqlSessionFactory dynamicSqlSessionFactory(DataSource dynamicDataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dynamicDataSource);
return sqlSessionFactoryBean.getObject();
}
}
- 创建
DynamicDataSource
类,实现数据源的动态切换:
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getCurrentDataSource();
}
}
- 创建
DataSourceContextHolder
类,用于保存当前线程使用的数据源标识:
public class DataSource
评论已关闭