Ribbon 负载均衡
实例总结:1两个service-provider 实例名称要一致
2消费者pom中引入starter-netflix-ribbon依赖
3重构RestTemplate模板类,加上@LoadBalanced注解
4使用RestTemplate类的getForObject(如:rt.getForObject(“http://eureka-provider/sayHello”,String.class);)
流程:Ribbon从EurekaClient获取服务列表,然后根据IPing判断是否可用,
则会根据负载均衡策略(父接口IRule)选择可用的服用
负载均衡策略: RoundRobinRule默认,线性轮询
WeightedResponseTimeRule 响应时间加权
BestAvailableRule :选择并发量小的服务
RandomRule :随机选择
原则:假如硬件性能差不多,使用默认的策略(RoundRobinRule)推荐
加入硬盘性能有差别,使用WeightedResponseTimeRule
负载均衡策略配置: 1全局配置,配置类中配置负载均衡策略:
@Bean
public IRule iRule(){
return new RandomRule();//重新选择负载均衡算法
}
2 分实例配置: 1配置文件中配置特定实例对应的负载均衡策略
比如:eureka-provider:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
2 发请求前 加this.loadBalancerClient.choose(“eureka-provider”);
方式一(全局的负载均衡的配置-随机分发)
在myconfig配置类中加入iRule()方法
package com.example.eurekaconsumer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.boot.web.client.RestTemplateBuilder;
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 myconfig {
@Bean
//负载均衡
@LoadBalanced
public RestTemplate restTemplate(RestTemplateBuilder builder){
return builder.build();
}
//全局的负载均衡的配置-随机分发
@Bean
public IRule isRule(){
return new RandomRule();//重新选择负载均衡算法
}
}
方式二(分实例配置)
首先在controller层加入LoadBalancerClient,然后通过choose方法选择对应的服务的提供者 ServiceInstance serviceInstance = this.loadBalancerClient.choose(“eureka-provider”);
package com.example.eurekaconsumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class TestController {
@Autowired
private RestTemplate rt;
@Autowired
private LoadBalancerClient loadBalancerClient;
@RequestMapping("/hi")
public String hi(){
ServiceInstance serviceInstance = this.loadBalancerClient.choose("eureka-provider");
return rt.getForObject("http://eureka-provider/sayhello",String.class);
}
}
最后在配置文件application.yml加入如下配置
eureka-provider:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
测试运行的效果便是两个provider的端口号是随机分发,每次刷新出现的都不固定。