【发布时间】:2016-09-30 09:12:07
【问题描述】:
我使用AbstractRoutingDataSource 动态更改数据源并使用ThreadLocal 设置currentLookupKey。当我每个 http 请求只使用一个数据源时,它工作得很好。我用JpaRepository
@Component
@Primary
public class RoutingDataSource extends AbstractRoutingDataSource {
@Autowired
private DatabaseMap databaseMap;
@Override
public void afterPropertiesSet() {
setTargetDataSources(databaseMap.getSourcesMap());
setDefaultTargetDataSource(databaseMap.getSourcesMap().get("DEFAULT"));
super.afterPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey() {
return DatabaseContextHolder.getDatabaseType();
}
}
public class DatabaseContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
public static void setDatabaseType(String string) {
contextHolder.set(string);
}
public static String getDatabaseType() {
return (String) contextHolder.get();
}
public static void clearDatabaseType() {
contextHolder.remove();
}
}
当我尝试在我的 REST 控制器中获取数据时,我只从一个数据库中获取数据。
我的 REST 控制器中的一些代码
DatabaseContextHolder.setDatabaseType("db1");
//here I get data from db1 as expected
//I use JpaRepository
DatabaseContextHolder.clearDatabaseType();
DatabaseContextHolder.setDatabaseType("db2");
//here I should get data from db2 but get from db1
我尝试调试,看起来Spring在http请求中只获取了一次数据源。
这个方法只被调用一次。
@Override
public Connection getConnection() throws SQLException {
return determineTargetDataSource().getConnection();
}
有什么办法可以强制Spring改变数据源。
【问题讨论】:
-
即使m面临同样的问题,你有没有得到任何解决方案
-
很遗憾我没有
-
嘿@mariusz2108,到目前为止,您有什么解决方案吗?我刚刚遇到了同样的问题。
-
@AnkitSingodia 我猜你想为同一个请求多次切换。您可以编辑问题以显示您正在切换的位置,包括方法中的任何
@Transactional注释吗?
标签: java spring datasource