微服务spring cloud之Ribbon实现客户端负载均衡 - 二

通过spring cloud ribbon的封装,我么在微服务架构中使用客户端负载均衡变得相对简单,可以分为两步

1. 服务提供者启动多个服务实例,并注册至一个或者多个相关联的服务注册中心

2. 服务消费者直接通过调用被@LoadBalanced注解修饰过的RestTemplate来实现面向服务的接口调用。

代码如下

pom.xml 



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.7.RELEASE
         
    
    com.kklixin
    ribbon-consumer
    1.0
    ribbon-consumer
    Demo project for Spring Boot

    
        1.8
        Greenwich.SR2
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-server
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-ribbon
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


application.yml的配置

server:
  port: 8081
spring:
  application:
    name: consumer-service
eureka:
  client:
    service-url:
      defaultZone: http://peer1:1111/eureka,http://peer2:1112/eureka

启动类

package com.kklixin.ribbonconsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
public class RibbonConsumerApplication {

    @Bean
    @LoadBalanced
    RestTemplate restTemplate(){
        return new RestTemplate();
    }
    public static void main(String[] args) {
        SpringApplication.run(RibbonConsumerApplication.class, args);
    }

}

服务调用代码

package com.kklixin.ribbonconsumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController {
    @Autowired
    RestTemplate restTemplate;

    @RequestMapping(value="/consumer",method = RequestMethod.GET)
    public String helloConsumer(){
        return restTemplate.getForEntity("http://hello-service/hello",String.class).getBody();
    }
}

上面代码和上一篇eureka高可用注册中心一起实现服务发现与客户端负载均衡

RestTemplate详解

Ribbon中可以通过RestTemplate发起客户端负载均衡请求,但RestTemplate存在不同的请求类型和参数类型调用实现

1. Get请求

        1)getForEntity方法封装了返回的请求状态,请求头,以及请求体的信息,参数分别为字符串类型的请求地址,以及泛型的返回值类型,url可通过服务名调用,如(http://hello-service/hello)

         RestTemplate restTemplate = new RestTemplate ();

         restTemplate.getForEntity("url",String.class).getBody();

       2 ) 请求参数分别为带占位符的url(http://hello-service/hello?to={1}),泛型的返回值类型,以及占位符替换的请求参数

         RestTemplate restTemplate = new RestTemplate ();

         restTemplate.getForEntity("url",String.class,"hello").getBody();

     3)请求参数分别为带占位符的url(http://hello-service/hello?to={target}),泛型的返回值类型,以及Map类型的替换参数,

而map的key及是target

        RestTemplate restTemplate = new RestTemplate ();

         restTemplate.getForEntity("url",String.class,map).getBody();

而当只关注返回信息中的body内容时,restTemplate也提供了getForObject方法,同样提供了三种重载的方法类型,参数同getForEntity一致

2. POST请求

    同getForEntity一样,RestTemplate对post请求也提供了三种重载的方法postForEntity

    1)postForEntity(String url,Object request,Class responseType,Object...urlParams)

    2)postForEntity(String url,Object request,Class responseType,Map urlParams)

    3) postForEntity(String url,Object request,Class responseType)

    其中request可以是一个HttpEntity对象,也可以是普通对象,但如果是普通对象及非HttpEntity对象时RestTemplate会将请求对象转换成一个HttpEntity对象处理

3 PUT 请求 同样实现了三种重载的方法

    1) put(String url,Object request,Object... urlParams)

    2) put(String url,Object request,Map... urlParams)

    3) put(String url,Object request)
     

    put函数没有返回值,所以不需要指定返回类型,其他参数同postForEntity

4 DELETE 请求同样实现了三种重载方法,具体调用同put相同

    

    1) delete(String url,Object request,Object... urlParams)

    2) delete(String url,Object request,Map... urlParams)

    3) delete(String url,Object request)

 

负载均衡策略

在ribbon中,实现了非常多的选择策略,而负载均衡策略依赖于IRule接口的实现

 负载均衡策略有

  1)AbstractLoadBalancerRule  负载均衡策略的抽象类,在该类中定义了负载均衡器ILoadBalancer对象,该对象

       可以在具体实现选择服务策略时,获取到一些负载均衡器中维护的信息来作为分配依据,并以此设计针对特定场景的

      高效策略

  2)RandomRule  该策略是从服务清单中随机选择一个服务实例

  3)RoundRobinRule  该策略是按照线性轮询的方式依次选择每个服务实例

  4)RetyRule 该策略具备了一个重试机制的实例选择功能,默认使用RoundRobinRule,对内部定义的策略进行反复尝试,若期间能获取到服务实例则返回,若不能则根据设置的结束时间(maxRetryMills+choose方式开始执行的时间戳)来返回空值

  5)WeightedResponseTimeRule  该策略是对RoundRobin的扩展,增加了根据实例的运行情况来计算权重,并根据权重来选择服务实例,已达到更优的分配效果

  6)ClientConfigEnabledRoundRobinRule 该策略因为本身没有实现特殊的处理逻辑,所以一般不会直接使用,它的作用是通过继承该策略,在子类中做一些自定义处理逻辑,该策略默认实现了线性轮询策略

  7) BestAvailableRule 该策略继承自ClientConfigEnabledRoundRobinRule,该策略的作用是选出可用实例中压力最小的实例

  8)PredicateBasedRule 该策略也继承自ClientConfigEnabledRoundRobinRule,是一个抽策略,这是一个基于Predicate实现的策略,Predicate是Google Guava Collection工具对集合进行过滤的条件接口,该策略是通过子类中实现的Predicate逻辑来过滤一部分服务实例,然后以线性轮询的方式从过滤后的实例中选择一个。

9)ZoneAvoidanceRule 该策略是PredicateBasedRule的具体实现类,完全遵循了父类的先过滤后选择实例,但过滤条件更多。

 

与Eureka结合,此时会触发Eureka中对Ribbon的自动化配置

1) ServerList的维护机制将被com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList的实例所替代,该类会将服务清单列表交由eureka的服务治理机制来维护

2 IPing 将被com.netflix.niws.loadbalancer.NIWSDiscoveryPing的实例替代,同样将实例的检查任务交由eureka的服务治理框架来维护。

Eureka区别于Zookeeper的CP(一致性,可靠性),强调了CAP理论中的AP(可用性,可靠性),Eureka为了获取更高的服务可用性,牺牲了一定的一致性,而erueka为了增强服务调用到故障实例的处理,开发者需要通过简单的配置来实现重试策略(在Brixton版本及更低的版本中重试机制需要自定义实现)

你可能感兴趣的:(spring,cloud)