zoukankan      html  css  js  c++  java
  • SpringCloud教程二:Ribbon(服务调用,负载均衡一)

    一、概述

    Spring cloud有两种服务调用方式,一种是ribbon+restTemplate,另一种是feign,这里先将第一种。Spring Cloud Ribbon是一个基于HTTP和TCP的客户端负载均衡工具,它基于Netflix Ribbon实现。通过Spring Cloud的封装,可以让我们轻松地将面向服务的REST模版请求自动转换成客户端负载均衡的服务调用。Spring Cloud Ribbon虽然只是一个工具类框架,它不像服务注册中心、配置中心、API网关那样需要独立部署,但是它几乎存在于每一个Spring Cloud构建的微服务和基础设施中。因为微服务间的调用,API网关的请求转发等内容,实际上都是通过Ribbon来实现的,包括后续我们将要介绍的Feign,它也是基于Ribbon实现的工具。所以,对Spring Cloud Ribbon的理解和使用,对于我们使用Spring Cloud来构建微服务非常重要。

    二、原理

    Ribbon 实现负载均衡,基本用法是注入一个 RestTemplate,并在 RestTemplate 上使用 @LoadBalanced,才能使 RestTemplate 具备负载均衡能力。

    @LoadBalanced

    /**
     * Annotation to mark a RestTemplate bean to be configured to use a LoadBalancerClient
     * @author Spencer Gibb
     */
    @Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Inherited
    @Qualifier
    public @interface LoadBalanced {
    }

     

    这个注解标注一个 RestTemplate,使用 LoadBalancerClient,那么 LoadBalancerClient 又是什么?

    LoadBalancerClient

    /**
     * Represents a client side load balancer
     * @author Spencer Gibb
     */
    public interface LoadBalancerClient extends ServiceInstanceChooser {
    
        <T> T execute(String serviceId, LoadBalancerRequest<T> request) throws IOException;
    
        <T> T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest<T> request) throws IOException;
        
        URI reconstructURI(ServiceInstance instance, URI original);
    }

    LoadBalancerClient 又扩展了 ServiceInstanceChooser 接口

    public interface ServiceInstanceChooser {
    
        ServiceInstance choose(String serviceId);
    }

    方法解释

    • ServiceInstance choose(String serviceId):根据 serviceId,结合负载均衡器,选择一个服务实例
    • <T> T execute(String serviceId, LoadBalancerRequest<T> request):使用 LoadBalancer 的 serviceInstance 为置顶的服务执行请求
    • <T> T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest<T> request):使用来自 LoadBalancer 的 ServiceInstance 为指定的服务执行请求,是上一个方法的重载,是上一个方法的细节实现
    • URI reconstructURI(ServiceInstance instance, URI original):使用主机 ip、port 构建特定的 URI,供 RIbbon 内部使用。Ribbon 使用服务名称的 URI 作为host。如:http://instance-id/path/to/service

    三、实践

    这个实践代码基于上一遍:SpringCloud教程一。

    ①首页创建eureka-server,service-hello配置端口为8763,启动二者,再启动教程一种service-hello(8762)

    打开:http://localhost:8761/

    service-hello在eureka-server注册了2个实例,这就相当于一个小的集群。

    ②创建service-ribbon

    在它的pom.xml文件分别引入起步依赖spring-cloud-starter-eureka、spring-cloud-starter-ribbon、spring-boot-starter-web

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.wyma</groupId>
        <artifactId>service-ribbon</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <name>service-ribbon</name>
        <description>Demo project for Spring Boot</description>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.2.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-eureka</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-ribbon</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-dependencies</artifactId>
                    <version>Dalston.RC1</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
        <repositories>
            <repository>
                <id>spring-milestones</id>
                <name>Spring Milestones</name>
                <url>https://repo.spring.io/milestone</url>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
            </repository>
        </repositories>
    
    
    </project>

    在工程的配置文件指定服务的注册中心地址为http://localhost:8761/eureka/,程序名称为 service-ribbon,程序端口为8764。配置文件application.yml如下:

    eureka:
      client:
        serviceUrl:
          defaultZone: http://localhost:8761/eureka/
    server:
      port: 8764
    spring:
      application:
        name: service-ribbon

    在工程的启动类中,通过@EnableDiscoveryClient向服务中心注册;并且向程序的ioc注入一个bean: restTemplate;并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能。

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

    写一个测试类HelloService,通过之前注入ioc容器的restTemplate来消费service-hello服务的“/hello”接口,在这里我们直接用的程序名替代了具体的url地址,在ribbon中它会根据服务名来选择具体的服务实例,根据服务实例在请求的时候会用具体的url替换掉服务名,代码如下:

    @Service
    public class HelloService {
        @Autowired
        RestTemplate restTemplate;
    
        public String helloService(String name) {
            return restTemplate.getForObject("http://SERVICE-HELLO/hello?name="+name,String.class);
        }
    }

    写一个controller,在controller中用调用HelloService 的方法,代码如下:

    @RestController
    public class HelloController {
        @Autowired
        HelloService helloService;
    
        @RequestMapping(value = "/hello")
        public String hello(@RequestParam String name){
            return helloService.helloService(name);
        }
    }

    在浏览器上多次访问http://localhost:8764/hello?name=51ma,浏览器交替显示:

    hello 51ma,i am from port:8763
    hello 51ma,i am from port:8762

    这说明当我们通过调用restTemplate.getForObject(“http://SERVICE-hello/hello?name=”+name,String.class)方法时,已经做了负载均衡,访问了不同的端口的服务实例。

    流程如下:

    • 一个服务注册中心,eureka server,端口为8761
    • service-hello工程跑了两个实例,端口分别为8762,8763,分别向服务注册中心注册
    • sercvice-ribbon端口为8764,向服务注册中心注册
    • 当sercvice-ribbon通过restTemplate调用service-hello的hello接口时,因为用ribbon进行了负载均衡,会轮流的调用service-hello:8762和8763 两个端口的hello接口;

     

    四、参考资料

    spring-cloud-ribbon

    springcloud ribbon with eureka

    五、源码

    加入qq群:Spring全家桶技术交流①群196165973,免费获取源码。

  • 相关阅读:
    C语言保留字
    N的阶乘末尾有多少个零?
    控制台初级玩法
    数据结构笔记#二分法查找
    数据结构应用实例#栈&单链表#简易计算器
    数据结构应用实例#栈#迷宫寻路
    数据结构笔记#栈
    #2028 Lowest Common Multiple Plus
    数据结构笔记#单链表
    #2018 母牛的故事
  • 原文地址:https://www.cnblogs.com/51ma/p/11903507.html
Copyright © 2011-2022 走看看