码迷,mamicode.com
首页 > 编程语言 > 详细

SpringCloud(2) 客户端的负载均衡Ribbon

时间:2018-07-31 23:36:00      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:.net   请求转发   直接   store   end   stc   负载   discover   framework   

和Nginx不同,Ribbon是客户端的负载均衡,Nginx是服务端的负载均衡

创建ribbon的demo项目

首先加入ribbon依赖

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>

修改配置文件 application.properties
server.port=9000
spring.application.name=ribbon-consumer
#自定义属性
# ribbon.listOfServers是固定的 stores是自己写的
stores.ribbon.listOfServers=http://localhost:8891,http://localhost:8892

然后自定义一个controller,返回值就是对应的哪个服务
/**
* 进行请求转发的接口
* @autor Guojs
* @date 2018/7/31 17:07
*/
@RestController
public class consumerController {

@Resource
private LoadBalancerClient balancerClient;

@RequestMapping("/consumer")
public String helloConsumer(){
//读取对应的配置
ServiceInstance instance = balancerClient.choose("stores");
//这个uri是经过负载均衡算法之后的
URI uri = URI.create(String.format("http://%s:%s", instance.getHost(), instance.getPort()));
return uri.toString();
}

}
然后启动上一遍的Eureka集群和两个服务提供者,再启动这个Ribbon访问http://localhost:9000/consumer
会发现默认使用的是轮询的负载均衡算法,一次http://localhost:8891一次http://localhost:8892轮询。

修改负载均衡算法:
1.修改配置文件
stores.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer
2.在主函数中写一个bean来覆盖默认的算法
@Bean
public IRule ribbonRule(){
return new RandomRule();
}
改进之后的Ribbon
引入eureka依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
简化配置文件,将ribbon在eureak中注册
server.port=9000
spring.application.name=ribbon-consumer
eureka.client.service-url.defaultZone=http://localhost:8877/eureka/,http://localhost:8898/eureka/

在Application中增加  @EnableDiscoveryClient(标识eureka的客户端)
@RibbonClient(name = "HELLO-SERVER",configuration = com.netflix.loadbalancer.RandomRule.class)(第一次参数是服务名,第二个参数是负载均衡算法,用于自定义负载均衡算法)
声明一个bean,用来调用服务
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
接下来看controller的修改,将原来直接调用服务url的方式改为调用服务名称,使用刚才声明的restTemplate来调用
@Resource
private RestTemplate restTemplate;

@RequestMapping("/consumer")
public String helloConsumer(){
return restTemplate.getForEntity("http://HELLO-SERVER/hello",String.class).getBody();
}
这样修改解决了之前在配置文件中硬写入服务地址的问题,但是还有单点故障没有解决,不过实战中ribbon不是这样使用的,每个eureka客户端单独声明一个ribbon(即:一个客户端独有一个ribbon)。

自带的负载均衡算法:

BestAvailableRule 选择一个最小的并发请求的服务检测每个服务,如果服务挂了,则忽略,在选择其中被请求最少的服务

AvailabilityFilteringRule
WeightedResponseTimeRule  加权轮询?根据相应时间分配一个weight,相应时间越长,weight越小,被选中的可能性越低。

RetryRule

RoundRobinRule

RandomRule 随机算法

ZoneAvoidanceRule

SpringCloud(2) 客户端的负载均衡Ribbon

标签:.net   请求转发   直接   store   end   stc   负载   discover   framework   

原文地址:https://www.cnblogs.com/sleepy-goblin/p/9398276.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!