1 回答
TA贡献1806条经验 获得超5个赞
我的意思是,你已经找到了完成这项任务的最佳方法AbstractRoutingDataSource。如果您有固定数量的用户,那么您可以使用以下方法的最简单方法:
public final class RoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return UserContextHolder.getUserName() + "DataSource";
}
}
以及配置:
@Bean
@Qualifier("user1DataSource")
public DataSource userOneDataSource() {
return DataSourceBuilder.create()
.username("user1")
.password("pass")
...
.build();
}
@Bean
@Qualifier("user2DataSource")
public DataSource userOneDataSource() {
return DataSourceBuilder.create()
.username("user2")
...
.build();
}
@Bean
@Primary
public RoutingDataSource dataSource(Map<String, DataSource> datasources) {
return new RoutingDataSource().dataSource(datasources);
}
如果您需要在运行时添加用户和数据源,您可以使用如下内容:
public final class RoutingDataSource extends AbstractRoutingDataSource {
private final ConcurrentHashMap<String, DataSource> dynamicDataSources = new ConcurrentHashMap<>();
@Override
protected Object determineCurrentLookupKey() {
return UserContextHolder.getUserName() + "_datasource";
}
@Override
protected DataSource determineTargetDataSource() {
String currentLookupKey = this.determineCurrentLookupKey().toString();
String userName = UserContextHolder.getUserName();
String password = UserContextHolder.getPassword();
return this.dynamicDataSources.computeIfAbsent(currentLookupKey, (key) -> DataSourceBuilder.create()
.driverClassName("your.driver.class")
.url("jdbc:same:url/here")
.username(userName)
.password(password)
.build());
}
}
添加回答
举报