View on GitHub

ScaleCube Reactive Microservices

The Future is reactive - The Future is right here!

Implementing Router

Service router controls the service endpoint selection when invoking remote service instances.

for example:

public class MyCanaryRouter implements Router {

  private ServiceRegistry serviceRegistry;

  public MyCanaryRouter(ServiceRegistry serviceRegistry) {
    this.serviceRegistry = serviceRegistry;
  }

  @Override
  public Optional<ServiceInstance> route(ServiceDefinition serviceDefinition) {
    RandomCollection<ServiceInstance> weightedRandom = new RandomCollection<>();
    serviceRegistry.serviceLookup(serviceDefinition.serviceName()).stream().forEach(instance -> {
      weightedRandom.add(
          Double.valueOf(instance.tags().get("Weight")),
          instance);
    });
    return Optional.of(weightedRandom.next());
  }
}

Constructor

To get a handle to the service registry the router may implement a constructor that accepts ServiceRegistry. using the service registry its possible to lookup currently active service instances and manually select the target service instance and then apply custom selection logic and return a selected ServiceInstance.

In the example above we select service instance by a Weighted Random of a given service tag.