Spring Cloud Alibaba 02_使用 ribbon 实现负载均衡

x33g5p2x  于2021-12-18 转载在 其他  
字(2.3k)|赞(0)|评价(0)|浏览(320)

Spring Cloud Alibaba 02_使用 ribbon 实现负载均衡

注:Ribbon 是 Netflix 提供的组件,不是 Alibaba 的组件

  • 修改 ConsumerConfiguration,添加 @LoadBalanced 注解
package com.blu.configuration;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class ConsumerConfiguration {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

}
  • 修改 ConsumerController 中的 index 方法:

Ribbon会将服务名 provider 解析为相应的 uri

@GetMapping("index")
public String index(){
	String result = restTemplate.getForObject("http://provider/index", String.class);
    return "调用的端口为:"+ result;
}

这里的负载均衡策略默认是轮询

修改负载均衡策略

  • 随机算法:

只需修改配置文件即可:

server:
  port: 8100

provider:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
  • 基于权重的算法:

添加 NacosWeightedRule 类

package com.blu.configuration;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import org.springframework.beans.factory.annotation.Autowired;

public class NacosWeightedRule extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
        //读取配置文件
    }

    @Override
    public Server choose(Object key) {
        ILoadBalancer loadBalancer = this.getLoadBalancer();
        BaseLoadBalancer baseLoadBalancer = (BaseLoadBalancer) loadBalancer;
        //获取要请求的服务名
        String name = baseLoadBalancer.getName();
        //获取服务发现的相关API
        NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
        try{
            Instance instance = namingService.selectOneHealthyInstance(name);
            return new NacosServer(instance);
        } catch (NacosException e) {
            e.printStackTrace();
            return null;
        }

    }
}

修改配置文件,指定负载均衡策略的类:

server:
  port: 8100

provider:
  ribbon:
    NFLoadBalancerRuleClassName: com.blu.configuration.NacosWeightedRule

可在 nacos 中修改指定实例的权重:

相关文章