use of org.apache.shardingsphere.underlying.common.rule.DataNode in project chao-cloud by chaojunzi.
the class ShardingActualNodesComplete method refreshDatasource.
/**
* 动态刷新数据源
*
* @param dsName 数据源名称
* @param tableName 逻辑表
* @param nodes 真实表
*/
/**
* 动态刷新数据源
*/
static void refreshDatasource(String dsName, String tableName, Collection<String> nodes) {
ShardingDataSource shardingDataSource = SpringUtil.getBean(ShardingDataSource.class);
TableRule tableRule = shardingDataSource.getRuntimeContext().getRule().getTableRule(tableName);
// 1.动态刷新:actualDataNodes
List<DataNode> actualDataNodes = tableRule.getActualDataNodes();
nodes.forEach(n -> {
DataNode node = new DataNode(dsName, n);
if (!CollUtil.contains(actualDataNodes, node)) {
actualDataNodes.add(node);
}
});
//
Set<String> actualTables = Sets.newHashSet();
Map<DataNode, Integer> dataNodeIndexMap = Maps.newHashMap();
// 修改节点索引
CollUtil.forEach(actualDataNodes, (n, i) -> {
actualTables.add(n.getTableName());
dataNodeIndexMap.put(n, i);
});
EntityUtil.setProperty(tableRule, TableRule::getActualDataNodes, actualDataNodes);
// 2.动态刷新:actualTables
EntityUtil.setProperty(tableRule, new TypeReference<Set<String>>() {
}, actualTables);
// 3.动态刷新:dataNodeIndexMap
EntityUtil.setProperty(tableRule, new TypeReference<Map<DataNode, Integer>>() {
}, dataNodeIndexMap);
// 4.动态刷新:datasourceToTablesMap
Map<String, Collection<String>> datasourceToTablesMap = EntityUtil.getProperty(tableRule, new TypeReference<Map<String, Collection<String>>>() {
});
if (datasourceToTablesMap.containsKey(dsName)) {
Collection<String> tables = datasourceToTablesMap.get(dsName);
tables.addAll(nodes);
} else {
datasourceToTablesMap.put(dsName, actualTables);
}
}
Aggregations