springboot代码切换数据源
时间: 2023-09-10 11:12:02 浏览: 222
在Spring Boot中实现数据源切换的代码可以通过以下步骤完成:
1. 在启动类中,需要移除默认的数据库配置类(DataSourceAutoConfiguration),可以使用@SpringBootApplication注解的exclude属性实现。具体代码如下:
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class DbDemoApplication {
public static void main(String[] args) {
SpringApplication.run(DbDemoApplication.class, args);
}
}
```
2. 创建一个动态数据源类(DynamicDataSource),继承自AbstractRoutingDataSource,并实现determineCurrentLookupKey()方法,用于确定要使用的数据源。具体代码如下:
```java
import com.example.demo.utils.DataSourceUtil;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceUtil.getDB();
}
}
```
3. 创建一个数据源切换工具类(DataSourceUtil),用于设置和获取要使用的数据源名。具体代码如下:
```java
public class DataSourceUtil {
public static final String DEFAULT_DS = "db1";
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
public static void setDB(String dbType) {
contextHolder.set(dbType);
}
public static String getDB() {
return contextHolder.get();
}
public static void clearDB() {
contextHolder.remove();
}
}
```
4. 配置Spring的多数据源支持,需要继承AbstractRoutingDataSource,并实现determineCurrentLookupKey()方法,用于确定要使用的数据源。具体代码如下:
```java
public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {
protected DataSource determineTargetDataSource() {
Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
Object lookupKey = determineCurrentLookupKey();
DataSource dataSource = this.resolvedDataSources.get(lookupKey);
if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
dataSource = this.resolvedDefaultDataSource;
}
if (dataSource == null) {
throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
}
return dataSource;
}
protected abstract Object determineCurrentLookupKey();
}
```
通过以上步骤,你可以实现在Spring Boot中切换数据源的功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [Springboot设置多数据源,随时切换](https://blog.csdn.net/qiaodaima0/article/details/99710831)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文