1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.shardingsphere.sharding.route.engine.type.broadcast;
19
20 import com.google.common.collect.Sets;
21 import org.apache.shardingsphere.infra.route.context.RouteContext;
22 import org.apache.shardingsphere.infra.route.context.RouteMapper;
23 import org.apache.shardingsphere.infra.route.context.RouteUnit;
24 import org.apache.shardingsphere.sharding.route.engine.type.ShardingRouteEngine;
25 import org.apache.shardingsphere.sharding.rule.ShardingRule;
26 import org.apache.shardingsphere.sharding.rule.ShardingTable;
27
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.LinkedList;
32 import java.util.Set;
33 import java.util.concurrent.ThreadLocalRandom;
34
35
36
37
38 public final class ShardingDataSourceGroupBroadcastRoutingEngine implements ShardingRouteEngine {
39
40 @Override
41 public RouteContext route(final ShardingRule shardingRule) {
42 RouteContext result = new RouteContext();
43 Collection<Set<String>> broadcastDataSourceGroup = getBroadcastDataSourceGroup(getDataSourceGroup(shardingRule));
44 for (Set<String> each : broadcastDataSourceGroup) {
45 String dataSourceName = getRandomDataSourceName(each);
46 result.getRouteUnits().add(new RouteUnit(new RouteMapper(dataSourceName, dataSourceName), Collections.emptyList()));
47 }
48 return result;
49 }
50
51 private Collection<Set<String>> getBroadcastDataSourceGroup(final Collection<Set<String>> dataSourceGroup) {
52 Collection<Set<String>> result = new LinkedList<>();
53 for (Set<String> each : dataSourceGroup) {
54 result = getCandidateDataSourceGroup(result, each);
55 }
56 return result;
57 }
58
59 private Collection<Set<String>> getDataSourceGroup(final ShardingRule shardingRule) {
60 Collection<Set<String>> result = new LinkedList<>();
61 for (ShardingTable each : shardingRule.getShardingTables().values()) {
62 result.add(each.getDataNodeGroups().keySet());
63 }
64 return result;
65 }
66
67 private Collection<Set<String>> getCandidateDataSourceGroup(final Collection<Set<String>> dataSourceSetGroup, final Set<String> compareSet) {
68 Collection<Set<String>> result = new LinkedList<>();
69 if (dataSourceSetGroup.isEmpty()) {
70 result.add(compareSet);
71 return result;
72 }
73 Set<String> intersections;
74 boolean hasIntersection = false;
75 for (Set<String> each : dataSourceSetGroup) {
76 intersections = Sets.intersection(each, compareSet);
77 if (intersections.isEmpty()) {
78 result.add(each);
79 } else {
80 result.add(intersections);
81 hasIntersection = true;
82 }
83 }
84 if (!hasIntersection) {
85 result.add(compareSet);
86 }
87 return result;
88 }
89
90 private String getRandomDataSourceName(final Collection<String> dataSourceNames) {
91 return new ArrayList<>(dataSourceNames).get(ThreadLocalRandom.current().nextInt(dataSourceNames.size()));
92 }
93 }