All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.scalecube.services.routing.RoundRobinServiceRouter Maven / Gradle / Ivy

There is a newer version: 2.11.3.rc9
Show newest version
package io.scalecube.services.routing;

import io.scalecube.services.ServiceReference;
import io.scalecube.services.api.ServiceMessage;
import io.scalecube.services.registry.api.ServiceRegistry;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import org.jctools.maps.NonBlockingHashMap;

public class RoundRobinServiceRouter implements Router {

  private final Map counterByServiceName = new NonBlockingHashMap<>();

  @Override
  public Optional route(ServiceRegistry serviceRegistry, ServiceMessage request) {
    List serviceInstances = serviceRegistry.lookupService(request);
    if (serviceInstances.isEmpty()) {
      return Optional.empty();
    } else if (serviceInstances.size() == 1) {
      return Optional.of(serviceInstances.get(0));
    } else {
      AtomicInteger counter =
          counterByServiceName.computeIfAbsent(request.qualifier(), or -> new AtomicInteger());
      int index = (counter.incrementAndGet() & Integer.MAX_VALUE) % serviceInstances.size();
      return Optional.of(serviceInstances.get(index));
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy