Interface LoadBalancer<T>

  • Type Parameters:
    T - Base type of messages that can be handled by this load balancer.
    All Known Subinterfaces:
    RpcLoadBalancer
    All Known Implementing Classes:
    DefaultLoadBalancer, DefaultRpcLoadBalancer
    Functional Interface:
    This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

    @FunctionalInterface
    public interface LoadBalancer<T>
    Load balancer for unicast messaging.

    Implementations of this interface are responsible for unicast message routing within a MessagingChannel. Channel calls the route(Object, LoadBalancerContext) method of this interface every time when it is going to perform a unicast operation (f.e. send(...) or request(...)). Implementations of this method must select one of the cluster nodes from the provided context. The selected cluster node will be used by the channel as a messaging operation target.

    Below is the example that uses a modulo-based approach for load balancing:

    
    public class ExampleLoadBalancer implements LoadBalancer<Object> {
        @Override
        public ClusterNodeId route(Object msg, LoadBalancerContext ctx) {
            // Calculate position of a destination node within the cluster topology.
            int idx = Math.abs(msg.hashCode() % ctx.size());
    
            // Select the destination node
            // Note that nodes are always sorted by their IDs within the topology.
            return ctx.topology().nodes().get(idx).id();
        }
    }
    

    Instances of this interface can be registered via MessagingChannel.withLoadBalancer(LoadBalancer) or MessagingChannelConfig.setLoadBalancer(LoadBalancer) methods.

    See Also:
    MessagingService, MessagingChannel.withLoadBalancer(LoadBalancer)
    • Method Detail

      • route

        ClusterNodeId route​(T msg,
                            LoadBalancerContext ctx)
                     throws LoadBalancerException
        Selects one of the cluster nodes from the load balancer context. Note that the provided context contains only those nodes that are capable of receiving messages of this channel (i.e. have MessageReceiver) and match the channel's topology filtering rules.

        Returning null from this method (if target node can't be selected for some reason) will cause message sending operation to fail with LoadBalancerException.

        Parameters:
        msg - Message.
        ctx - Load balancer context.
        Returns:
        Node that should be used for the messaging operation.
        Throws:
        LoadBalancerException - if failed to perform load balancing.