Search in sources :

Example 51 with Message

use of io.scalecube.transport.Message 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

Message (io.scalecube.transport.Message)51 BaseTest (io.scalecube.testlib.BaseTest)31 Test (org.junit.Test)31 CountDownLatch (java.util.concurrent.CountDownLatch)28 Observable (rx.Observable)10 Member (io.scalecube.cluster.Member)8 Microservices (io.scalecube.services.Microservices)6 TimeUnit (java.util.concurrent.TimeUnit)6 Logger (org.slf4j.Logger)6 LoggerFactory (org.slf4j.LoggerFactory)6 ServiceCall (io.scalecube.services.ServiceCall)5 Collections (java.util.Collections)5 Executors (java.util.concurrent.Executors)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 Schedulers (rx.schedulers.Schedulers)5 List (java.util.List)4 Subscription (rx.Subscription)4 PublishSubject (rx.subjects.PublishSubject)4 Subject (rx.subjects.Subject)4 MetricRegistry (com.codahale.metrics.MetricRegistry)3