WeightConsistentHashLoadBalancer extends AbstractLoadBalancer { @Override public ProviderInfo doSelect(SofaRequest request, List<ProviderInfo> providerInfos) { String interfaceId = request.getInterfaceName(); String method = request.getMethodName(); String key = interfaceId + "#" + method; int hashcode = providerInfos.hashCode(); Selector selector = selectorCache.get(key); if (selector == null || selector.getHashCode() != hashcode) { selector = new Selector(interfaceId, method, providerInfos, hashcode); selectorCache.put(key, selector); } return selector.select(request); } WeightConsistentHashLoadBalancer(ConsumerBootstrap consumerBootstrap); @Override ProviderInfo doSelect(SofaRequest request, List<ProviderInfo> providerInfos);  }
@Test public void doSelect() throws Exception { WeightConsistentHashLoadBalancer loadBalancer = new WeightConsistentHashLoadBalancer(null); Map<Integer, Integer> cnt = new HashMap<Integer, Integer>(40); int size = 20; int total = 100000; SofaRequest request = new SofaRequest(); request.setInterfaceName(ConsistentHashLoadBalancerTest.class.getName()); request.setMethod(ConsistentHashLoadBalancerTest.class.getMethod("doSelect")); for (int i = 0; i < size; i++) { cnt.put(9000 + i, 0); } List<ProviderInfo> providers = buildDiffWeightProviderList(size); long start = System.currentTimeMillis(); for (int i = 0; i < total; i++) { ProviderInfo provider = loadBalancer.doSelect(request, providers); int port = provider.getPort(); cnt.put(port, cnt.get(port) + 1); } long end = System.currentTimeMillis(); System.out.println("elapsed" + (end - start) + "ms"); System.out.println("avg " + (end - start) * 1000 * 1000 / total + "ns"); int count = 0; for (int i = 0; i < size; i++) { if (cnt.get(9000 + i) > 0) { count++; } } Assert.assertTrue(count == 1); }
@Test public void testWeight() throws Exception { WeightConsistentHashLoadBalancer loadBalancer = new WeightConsistentHashLoadBalancer(null); SofaRequest request = new SofaRequest(); request.setInterfaceName(ConsistentHashLoadBalancerTest.class.getName()); request.setMethod(ConsistentHashLoadBalancerTest.class.getMethod("doSelect")); int size = 20; int total = 100000; List<ProviderInfo> providers = buildDiffWeightProviderList(size); Map<Integer, Integer> map = new HashMap(total * 2); for (int i = 0; i < total; i++) { request.setMethodArgs(new Object[] { "method" + i }); ProviderInfo provider = loadBalancer.doSelect(request, providers); Integer key = provider.getPort(); if (map.containsKey(key)) { int count = map.get(key); map.put(key, ++count); } else { map.put(key, 0); } } Set<Map.Entry<Integer, Integer>> set = map.entrySet(); Iterator<Map.Entry<Integer, Integer>> iterator = set.iterator(); while (iterator.hasNext()) { Map.Entry<Integer, Integer> entry = iterator.next(); int port = entry.getKey() - 9000; Assert.assertTrue(entry.getValue() > 500 * port * 0.90); Assert.assertTrue(entry.getValue() < 500 * port * 1.10); } }