分布式环境 mybatis切换数据源,不通过xml配置文件的方式,通过读取txt文件来动态连接数据库
时间: 2023-12-05 15:03:11 浏览: 75
可以通过自定义数据源的方式来实现动态连接数据库。以下是一个简单的示例:
首先,创建一个`DynamicDataSource`类,继承`AbstractRoutingDataSource`,并实现`determineCurrentLookupKey`方法,该方法返回当前使用的数据源的key:
```java
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDataSourceKey();
}
}
```
然后,创建一个`DataSourceContextHolder`类,用于保存当前线程使用的数据源的key:
```java
public class DataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
public static void setDataSourceKey(String key) {
contextHolder.set(key);
}
public static String getDataSourceKey() {
return contextHolder.get();
}
public static void clearDataSourceKey() {
contextHolder.remove();
}
}
```
接下来,创建一个`DataSourceConfig`类,用于配置多个数据源,并创建`DynamicDataSource`实例:
```java
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties("datasource.master")
public DataSource masterDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("datasource.slave")
public DataSource slaveDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public DynamicDataSource dynamicDataSource() {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put("master", masterDataSource());
targetDataSources.put("slave", slaveDataSource());
DynamicDataSource dataSource = new DynamicDataSource();
dataSource.setTargetDataSources(targetDataSources);
dataSource.setDefaultTargetDataSource(masterDataSource());
return dataSource;
}
}
```
在`application.yml`中,配置每个数据源的属性:
```yaml
datasource:
master:
url: jdbc:mysql://localhost:3306/master?useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
slave:
url: jdbc:mysql://localhost:3306/slave?useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
```
最后,在需要切换数据源的时候,通过读取txt文件来获取目标数据源的key,并将其保存到`DataSourceContextHolder`中:
```java
public class DataSourceSwitcher {
public static void switchTo(String dataSourceKey) {
DataSourceContextHolder.setDataSourceKey(dataSourceKey);
}
public static void switchToMaster() {
switchTo("master");
}
public static void switchToSlave() {
switchTo("slave");
}
public static void switchToFromTxt() throws IOException {
File file = new File("datasource.txt");
if (!file.exists()) {
throw new FileNotFoundException("datasource.txt not found!");
}
BufferedReader reader = new BufferedReader(new FileReader(file));
String dataSourceKey = reader.readLine();
reader.close();
switchTo(dataSourceKey);
}
}
```
这样,就可以在运行时通过读取txt文件来动态切换数据源了。
阅读全文