RoundRobinLoadBalancer extends AbstractLoadBalancer { @Override public ProviderInfo doSelect(SofaRequest request, List<ProviderInfo> providerInfos) { String key = getServiceKey(request); int length = providerInfos.size(); PositiveAtomicCounter sequence = sequences.get(key); if (sequence == null) { sequences.putIfAbsent(key, new PositiveAtomicCounter()); sequence = sequences.get(key); } return providerInfos.get(sequence.getAndIncrement() % length); } RoundRobinLoadBalancer(ConsumerBootstrap consumerBootstrap); @Override ProviderInfo doSelect(SofaRequest request, List<ProviderInfo> providerInfos);  }
@Test public void doSelect() throws Exception { RoundRobinLoadBalancer loadBalancer = new RoundRobinLoadBalancer(null); Map<Integer, Integer> cnt = new HashMap<Integer, Integer>(); int size = 20; int total = 190000; SofaRequest request = new SofaRequest(); { for (int i = 0; i < size; i++) { cnt.put(9000 + i, 0); } List<ProviderInfo> providers = buildSameWeightProviderList(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(); LOGGER.info("elapsed" + (end - start) + "ms"); LOGGER.info("avg " + (end - start) * 1000 * 1000 / total + "ns"); int avg = total / size; for (int i = 0; i < size; i++) { Assert.assertTrue(avg == cnt.get(9000 + i)); } } { 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(); LOGGER.info("elapsed" + (end - start) + "ms"); LOGGER.info("avg " + (end - start) * 1000 * 1000 / total + "ns"); int avg = total / size; for (int i = 0; i < size; i++) { Assert.assertTrue(avg == cnt.get(9000 + i)); } } }