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.

The code snippet below demonstrates service instance selection by a Weighted Random of a given service tag.

public class CanaryTestingRouter implements Router {

  @Override
  public Optional route(ServiceRegistry serviceRegistry, 
      ServiceMessage request) {
    RandomCollection weightedRandom = new RandomCollection<>();
    serviceRegistry.lookupService(request.qualifier())
        .forEach(sr -> 
		weightedRandom.add(
		  Double.valueOf(sr.tags().get("Weight")), sr));
    return Optional.of(weightedRandom.next());
  }

  @Override
  public List routes(ServiceRegistry serviceRegistry, 
      ServiceMessage request) {
    return serviceRegistry.lookupService(request.qualifier());
  }
}

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, manually select the target service instance, apply custom selection logic and return a selected ServiceInstance.