首页 > 编程语言 > 详细

Spring Cloud Alibaba 03:Ribbon负载均衡

时间:2020-12-02 19:54:21      阅读:37      评论:0      收藏:0      [点我收藏+]

Nacos中默认继承Ribbon

在上一篇文章基础上,Consumer模块配置类新增@LoadBalanced注解

@Configuration
public class ConsumerConfig {

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

ConsumerController改造

@RestController
public class ConsumerController {

    private final DiscoveryClient discoveryClient;
    private final RestTemplate restTemplate;
    //访问服务提供者服务的前缀,http://服务名
    private static final String REST_URL_PREFIX = "http://provider";

    @Autowired
    public ConsumerController(DiscoveryClient discoveryClient, RestTemplate restTemplate) {
        this.discoveryClient = discoveryClient;
        this.restTemplate = restTemplate;
    }


    @GetMapping("/instances")
    public List<ServiceInstance> getInstances() {
        return discoveryClient.getInstances("provider");
    }

    @GetMapping("/index")
    public String index() {
        return "consumer远程调用provier:" + this.restTemplate.getForObject(REST_URL_PREFIX + "/index", String.class);
    }
}

默认采用轮询算法,常用的还有随机和权重算法

随机

server:
  port: 9090

# 负载均衡策略 服务名+ribbon+策略(不配置默认使用轮询策略)
provider:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

Nacos 权重

public class NacosWeightedRule extends AbstractLoadBalancerRule {

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

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

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

    @Override
    public Server choose(Object o) {
        ILoadBalancer loadBalancer = this.getLoadBalancer();
        BaseLoadBalancer baseLoadBalancer = (BaseLoadBalancer) loadBalancer;
        //获取要请求的微服务名称
        String name = baseLoadBalancer.getName();
        //获取服务发现的相关API
        NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
        try {
            Instance instance = namingService.selectOneHealthyInstance(name);
            log.info("选择的实例是port={},instance={}", instance.getPort(), instance);
            return new NacosServer(instance);
        } catch (NacosException e) {
            e.printStackTrace();
            return null;
        }
    }
}
server:
  port: 9090

# 负载均衡策略 服务名+ribbon+策略(不配置默认使用轮询策略)
provider:
  ribbon:
    NFLoadBalancerRuleClassName: com.godfrey.config.NacosWeightedRule

默认权重都是1,修改权重再进行测试

技术分享图片

Spring Cloud Alibaba 03:Ribbon负载均衡

原文:https://www.cnblogs.com/MessiXiaoMo3334/p/14075316.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!