You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

26 lines
965 B

3 months ago
// DynamicDataSource.java
package com.example.web.config;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
// 线程本地变量:存储当前线程使用的数据源名称(保证线程安全)
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
// 设置数据源(供AOP切面调用,切换数据源)
public static void setDataSourceKey(String dataSourceKey) {
contextHolder.set(dataSourceKey);
}
// 清除数据源(线程结束时调用,避免线程池复用导致的数据源混乱)
public static void clearDataSourceKey() {
contextHolder.remove();
}
// 路由方法:返回当前线程的数据源名称(Spring会根据此方法选择对应的数据源)
@Override
protected Object determineCurrentLookupKey() {
return contextHolder.get();
}
}