一、Ribbon介绍

Ribbon是Netflix公司推出的HTTP和TCP的客户端负载均衡工具

ribbon特点:

简化远程调用代码内置很多负载均衡算法

1.1 服务端负载均衡

负载均衡算法在服务端,服务端维护服务列表

1.2 客户端负载均衡

负载均衡算法在客户端 客户端维护服务列表

二、如何使用Ribbon

1.新版的eureka依赖以及集成了Ribbon依赖,所以可以不引用

org.springframework.cloud

spring-cloud-starter-netflix-ribbon

2.声明restTemplate时使用@LoadBalanced

3.restTemplate请求远程服务时,ip端口替换为服务名

String url="http://EUREKA-PROVIDER/goods/findById/"+id;

Goods goods = restTemplate.getForObject(url, Goods.class);

4.测试

启动2个provider

controller中添加如下代码:

goods.setTitle(goods.getTitle()+"|端口号:"+port);

多次刷新,发现:ribbon客户端,默认使用轮询算法,经行负载均衡调用。

三、ribbon 负载均衡策略

四、设置ribbon 负载均衡策略

4.1 代码

consumer工程

1.MyRule 返回想要的规则即可

package com.liming.consumer.config;

import com.netflix.loadbalancer.IRule;

import com.netflix.loadbalancer.RandomRule;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class MyRule {

@Bean

public IRule rule(){

return new RandomRule();

}

}

2.启动类

@RibbonClient(name ="EUREKA-PROVIDER",configuration = MyRule.class)

总结:

1.irule的具体实现类,看到他带的几个策略的写法。 2.仿照策略的写法,自己写策略。 3.调用不同的其他微服务时,可以采用不同的策略。

4.2 配置

consumer工程

application.yml

EUREKA-PROVIDER: #远程服务名

ribbon:

NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #策略

作用:方便运维修改,重启。随时切换策略

相关链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: