spring cloud -- Ribbon

来源:互联网 发布:centos ftp 根目录 编辑:程序博客网 时间:2024/06/05 16:44

  1. 自定义负载均衡策略  
  2. springboot-h2.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule // 自定义使用随机策略,springboot-h2是服务应用名  
修改调用代码

  1. @RestController  
  2. public class RestTemplateController {  
  3.     @Autowired  
  4.     private RestTemplate restTemplate;  
  5.       
  6.     @Autowired  
  7.     private LoadBalancerClient loadBalancerClient;  
  8.       
  9.     @GetMapping("/template/{id}")  
  10.     public User findById(@PathVariable Long id) {  
  11.         ServiceInstance serviceInstance = this.loadBalancerClient.choose("springboot-h2");  
  12.         System.out.println("===" + ":" + serviceInstance.getServiceId() + ":" + serviceInstance.getHost() + ":"  
  13.                 + serviceInstance.getPort());// 打印当前调用服务的信息  
  14.         User u = this.restTemplate.getForObject("http://springboot-h2/user/" + id, User.class);  
  15.         System.out.println(u);  
  16.         return u;  
  17.     }  



Ribbon作为后端负载均衡器,比Nginx更注重的是请求分发而不是承担并发,可以直接感知后台动态变化来指定分发策略。它一共提供了7种负载均衡策略:

策略名策略声明策略描述实现说明BestAvailableRulepublic class BestAvailableRule extends ClientConfigEnabledRoundRobinRule选择一个最小的并发请求的server逐个考察Server,如果Server被tripped了,则忽略,在选择其中ActiveRequestsCount最小的serverAvailabilityFilteringRulepublic class AvailabilityFilteringRule extends PredicateBasedRule过滤掉那些因为一直连接失败的被标记为circuit tripped的后端server,并过滤掉那些高并发的的后端server(active connections 超过配置的阈值)使用一个AvailabilityPredicate来包含过滤server的逻辑,其实就就是检查status里记录的各个server的运行状态WeightedResponseTimeRulepublic class WeightedResponseTimeRule extends RoundRobinRule根据响应时间分配一个weight,响应时间越长,weight越小,被选中的可能性越低。一个后台线程定期的从status里面读取评价响应时间,为每个server计算一个weight。Weight的计算也比较简单responsetime 减去每个server自己平均的responsetime是server的权重。当刚开始运行,没有形成status时,使用roubine策略选择server。RetryRulepublic class RetryRule extends AbstractLoadBalancerRule对选定的负载均衡策略机上重试机制。在一个配置时间段内当选择server不成功,则一直尝试使用subRule的方式选择一个可用的serverRoundRobinRulepublic class RoundRobinRule extends AbstractLoadBalancerRuleroundRobin方式轮询选择server轮询index,选择index对应位置的serverRandomRulepublic class RandomRule extends AbstractLoadBalancerRule随机选择一个server在index上随机,选择index对应位置的serverZoneAvoidanceRulepublic class ZoneAvoidanceRule extends PredicateBasedRule复合判断server所在区域的性能和server的可用性选择server使用ZoneAvoidancePredicate和AvailabilityPredicate来判断是否选择某个server,前一个判断判定一个zone的运行性能是否可用,剔除不可用的zone(的所有server),AvailabilityPredicate用于过滤掉连接数过多的Server。


    @Bean    @LoadBalanced    RestTemplate restTemplate() {        return new RestTemplate();    }    @Bean    public IRule ribbonRule() {        return new RandomRule();//这里配置策略,和配置文件对应    }

this.loadBalancerClient.choose("service-B");//随机访问策略



配置properties file (sample-client.properties)


# Max number of retries    
ribbon.MaxAutoRetries=1     
# Max number of next servers to retry (excluding the first server)  
ribbon.MaxAutoRetriesNextServer=1 
 # Whether all operations can be retried for this client   
ribbon.OkToRetryOnAllOperations=true  
# Interval to refresh the server list from the source   
ribbon.ServerListRefreshInterval=2000   
# Connect timeout used by Apache HttpClient   
ribbon.ConnectTimeout=3000   
# Read timeout used by Apache HttpClient   
ribbon.ReadTimeout=3000   
# Initial list of servers, can be changed via Archaius dynamic property at runtime   
ribbon.listOfServers=testserver1:80,testserver2 :80,testserver3:80    
ribbon.EnablePrimeConnections=true  

Spring Cloud Netflix provides the following beans by default for ribbon (BeanType beanName: ClassName):

1、IClientConfig ribbonClientConfigDefaultClientConfigImpl

2、IRule ribbonRuleZoneAvoidanceRule

3、IPing ribbonPingNoOpPing

4、ServerList<Server> ribbonServerListConfigurationBasedServerList

5、ServerListFilter<Server> ribbonServerListFilterZonePreferenceServerListFilter

6、ILoadBalancer ribbonLoadBalancerZoneAwareLoadBalancer


1. 如果是对某个服务指定特定的负载均衡策略,则需要使用:RibbonClient注解,如下:

@Configurationpublic class FooConfiguration {    @Bean    public IPing ribbonPing() {        return new PingUrl(false,"/info.json");    }    /**     * 负载均衡策略     * @return     */    @Bean    public IRule ribbonRule() {//        return new BestAvailableRule(); //选择一个最小的并发请求的server//        return new WeightedResponseTimeRule(); //根据相应时间分配一个weight,相应时间越长,weight越小,被选中的可能性越低。//        return new RetryRule(); //对选定的负载均衡策略机上重试机制。//        return new RoundRobinRule(); //roundRobin方式轮询选择server//        return new RandomRule(); //随机选择一个server//        return new ZoneAvoidanceRule(); //复合判断server所在区域的性能和server的可用性选择server        return new AvailabilityFilteringRule();    }}

声明特定服务(foo)配置

@Configuration@RibbonClient(name = "foo", configuration = FooConfiguration.class)public class TestConfiguration {}

name:特定服务名称


2.

对所有服务指定特定负载均衡策略

指定所有服务的负载均衡策略使用注解:RibbonClients
import com.netflix.loadbalancer.AvailabilityFilteringRule;import com.netflix.loadbalancer.IPing;import com.netflix.loadbalancer.IRule;import com.netflix.loadbalancer.PingUrl;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * Created by meyer on 2017/2/22. */@Configurationpublic class RibbonConfiguration {    /**     * ping中心     * @return     */    @Bean    public IPing ribbonPing() {        return new PingUrl(false, "/info.json");    }    /**     * 负载均衡策略     * @return     */    @Bean    public IRule ribbonRule() {//        return new BestAvailableRule(); //选择一个最小的并发请求的server//        return new WeightedResponseTimeRule(); //根据相应时间分配一个weight,相应时间越长,weight越小,被选中的可能性越低。//        return new RetryRule(); //对选定的负载均衡策略机上重试机制。//        return new RoundRobinRule(); //roundRobin方式轮询选择server//        return new RandomRule(); //随机选择一个server//        return new ZoneAvoidanceRule(); //复合判断server所在区域的性能和server的可用性选择server        return new AvailabilityFilteringRule();    }}

触发配置

@EnableZuulProxy@EnableHystrix@SpringCloudApplication@RibbonClients(defaultConfiguration = {RibbonConfiguration.class})public class GatewayApplication {    public static void main(String[] args) {        SpringApplication.run(GatewayApplication.class, args);    }}

原创粉丝点击