Search in sources :

Example 1 with ServiceInstance

use of io.scalecube.services.ServiceInstance in project scalecube by scalecube.

the class RoundRobinServiceRouter method route.

@Override
public Optional<ServiceInstance> route(Message request) {
    String serviceName = request.header(ServiceHeaders.SERVICE_REQUEST);
    List<ServiceInstance> serviceInstances = serviceRegistry.serviceLookup(serviceName).stream().filter(instance -> instance.methodExists(request.header(ServiceHeaders.METHOD))).collect(Collectors.toList());
    if (serviceInstances.size() > 1) {
        AtomicInteger counter = counterByServiceName.computeIfAbsent(serviceName, or -> new AtomicInteger());
        int index = counter.incrementAndGet() % serviceInstances.size();
        return Optional.of(serviceInstances.get(index));
    } else if (serviceInstances.size() == 1) {
        return Optional.of(serviceInstances.get(0));
    } else {
        LOGGER.warn("route selection return null since no service instance was found for {}", serviceName);
        return Optional.empty();
    }
}
Also used : ServiceInstance(io.scalecube.services.ServiceInstance) Logger(org.slf4j.Logger) Collection(java.util.Collection) LoggerFactory(org.slf4j.LoggerFactory) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Collectors(java.util.stream.Collectors) ServiceRegistry(io.scalecube.services.ServiceRegistry) ConcurrentMap(java.util.concurrent.ConcurrentMap) List(java.util.List) ServiceHeaders(io.scalecube.services.ServiceHeaders) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Optional(java.util.Optional) Message(io.scalecube.transport.Message) Collections(java.util.Collections) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServiceInstance(io.scalecube.services.ServiceInstance)

Aggregations

ServiceHeaders (io.scalecube.services.ServiceHeaders)1 ServiceInstance (io.scalecube.services.ServiceInstance)1 ServiceRegistry (io.scalecube.services.ServiceRegistry)1 Message (io.scalecube.transport.Message)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 List (java.util.List)1 Optional (java.util.Optional)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 ConcurrentMap (java.util.concurrent.ConcurrentMap)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 Collectors (java.util.stream.Collectors)1 Logger (org.slf4j.Logger)1 LoggerFactory (org.slf4j.LoggerFactory)1