Bootstrap

dubbo3 负载均衡

dubbo3 负载均衡

负载均衡在分布式服务中任何一个解决方案都是要考虑的问题常见的分布式负载均衡算法也很多,对于 dubbo 来说负载均衡的配置可以在配置文件中设置全局的配置,也可以在服务注解 @DubboReference(loadbalance = LoadbalanceRules.SHORTEST_RESPONSE) @DubboService(protocol = "tri", loadbalance = LoadbalanceRules.CONSISTENT_HASH) 这里做配置,优先级最高的肯定是注解的方式

  • 轮训
  • 随机(随机 + weight)
  • 一致性 hash
  • 活跃度
  • 响应时间

服务端配置

package com.rpc.dubbo.loadbalance.random;

import com.rpc.dubbo.loadbalance.OrderService;
import org.apache.dubbo.common.constants.LoadbalanceRules;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;

/**
 * @author xl-9527
 * @since 2025/1/9
 **/
@DubboService(protocol = "tri", loadbalance = LoadbalanceRules.CONSISTENT_HASH)
public class OrderServiceImpl implements OrderService {

    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Override
    public String getOrderNumber(final Long orderId) {
        log.info("orderId -> {}", orderId);
        return UUID.randomUUID().toString();
    }
}

配置文件的方式配置

spring:
  application:
    name: dubbo-rpc-load-balance-consumer
dubbo:
  application:
    register-mode: instance
    metadata-type: remote
    qos-enable: false
  protocol:
    name: tri
    port: -1
  registry:
    address: ${NACOS_ADDRESS:127.0.0.1}:8848
    protocol: nacos
    group: xl-9527
    parameters:
      namespace: 096e0cc4-f6c3-428a-a712-71dd2c3162a4
  consumer:
    loadbalance: random

consumer 注解配置

package com.rpc.dubbo.loadbalance;

import org.apache.dubbo.common.constants.LoadbalanceRules;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * @author xl-9527
 * @since 2025/1/9
 **/
@Service
public class OrderServiceStub {

    private static final Logger log = LoggerFactory.getLogger(OrderServiceStub.class);

    @DubboReference(loadbalance = LoadbalanceRules.SHORTEST_RESPONSE)
    private OrderService orderService;

    public void getOrderNumber(final Long orderId) {
        log.info("orderId -> {}, num -> {}", orderId, orderService.getOrderNumber(orderId));
    }
}
;