Search in sources :

Example 1 with DataNode

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);
    }
}
Also used : TableRule(org.apache.shardingsphere.core.rule.TableRule) Set(java.util.Set) ShardingDataSource(org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource) DataNode(org.apache.shardingsphere.underlying.common.rule.DataNode) Collection(java.util.Collection) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Aggregations

Collection (java.util.Collection)1 Map (java.util.Map)1 Set (java.util.Set)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 TableRule (org.apache.shardingsphere.core.rule.TableRule)1 ShardingDataSource (org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource)1 DataNode (org.apache.shardingsphere.underlying.common.rule.DataNode)1