ClientLoadBalanceStrategy - minbox-projects/message-pipe GitHub Wiki

如果多个客户端同时绑定了同一个消息管道(MessagePipe),这时负载均衡策略就派上了用场。

框架本身默认只提供了一种随机均衡策略(RandomWeightedStrategy),根据随机数权重来获取排序后最近的一个客户端。

默认策略

RandomWeightedStrategy:

/**
 * The {@link ClientLoadBalanceStrategy} random strategy
 *
 * @author 恒宇少年
 * @see ClientLoadBalanceStrategy
 */
public class RandomWeightedStrategy implements ClientLoadBalanceStrategy {

    /**
     * lookup client load-balanced address {@link LoadBalanceNode#getClient()}
     * Lookup according to random weight admin address
     * get firstKey by {@link SortedMap#tailMap(Object)}
     *
     * @param clients message pipe bind clients
     * @return Load-balanced {@link ClientInformation}
     * @throws MessagePipeException message pipe exception
     */
    @Override
    public ClientInformation lookup(List<ClientInformation> clients) throws MessagePipeException {
        TreeMap<Double, LoadBalanceNode> nodes = new TreeMap();
        List<LoadBalanceNode> loadBalanceNodes =
                clients.stream().map(client -> new LoadBalanceNode(client)).collect(Collectors.toList());
        loadBalanceNodes.stream().forEach(node -> {
            double lastWeight = nodes.size() == 0 ? 0 : nodes.lastKey().doubleValue();
            nodes.put(node.getInitWeight() + lastWeight, node);
        });
        Double randomWeight = nodes.lastKey() * Math.random();
        SortedMap<Double, LoadBalanceNode> tailMap = nodes.tailMap(randomWeight, false);
        if (ObjectUtils.isEmpty(tailMap)) {
            throw new MessagePipeException("No load balancing node was found");
        }
        return nodes.get(tailMap.firstKey()).getClient();
    }
}

自定义策略

通过实现ClientLoadBalanceStrategy接口来完成自定义负载均衡策略算法,下面是一个简单的示例:

/**
 * 平滑负载均衡策略
 *
 * @author 恒宇少年
 */
public class SmoothClientLoadBalanceStrategy implements ClientLoadBalanceStrategy {
    @Override
    public ClientInformation lookup(List<ClientInformation> clients) throws MessagePipeException {
        if (!ObjectUtils.isEmpty(clients)) {
            // 实现平滑过渡负载均衡策略逻辑
        }
        // 不存在符合的客户端时,可以返回null
        return null;
    }
}

在上面策略中并没有实现负载算法,只是一个类示例。

启用策略

通过MessagePipeConfiguration#setLoadBalanceStrategy方法即可实现覆盖默认的负载均衡策略,如下所示:

@Bean
public MessagePipeConfiguration messagePipeConfiguration() {
    return MessagePipeConfiguration.defaultConfiguration()
            .setLoadBalanceStrategy(new SmoothClientLoadBalanceStrategy());
}