SpringCloud教程第二篇:Ribbon

一、ribbon简介

Ribbon is a client side load balancer which gives you a lot of control over the behaviour of HTTP and TCP clients. Feign already uses Ribbon, so if you are using @FeignClient then this section also applies.
—–摘自官网

官方给 Ribbon 的定义是一个用于远程调用的库,而它更为人熟知的作用是可以进行客户端的 Load Balance(负载均衡)。

Load Balance 对于任何一个分布式系统都是必要的基础功能,从实现角度而言,可以分为客户端 LB 和服务器端 LB。在日常工作中大家接触最多的应该是基于服务器的 LB 解决方案,例如通过 nginx 的反向代理,或是商用的 F5。但是今天的例子中会演示如何使用 Ribbon 搭建一个具有 LB 的客户端应用。

基础概念:
  • Rule:这个组件决定了从一堆候选服务器中返回哪个服务器地址进行远程调用的操作,即负载均衡策略。
  • Ping:在后台运行的组件,确认哪些服务器是存活可用的。
  • ServerList:当前可以用作 LB 的服务器列表,这个列表可以是静态的,也可以是动态的。如果是动态列表(例如从 Eurka 服务器获取),则会有一个后台线程按照时间间隔刷新列表。

二、创建 service-ribbon 项目

1. 基于上一篇文章的工程,启动eureka-client工程,端口为8762;将eureka-client配置文件的端口改为8763并启动,这时你会发现:eureka-client在eureka-server注册了2个实例,这就相当于一个小的集群。访问localhost:8761,如图所示:
在这里插入图片描述

如果改端口号为8763后不能启动,需要将eureka-client工程的启动配置:Single instance only的勾去掉,如图:
在这里插入图片描述

2. 重新建一个module的spring-boot工程:service-ribbon,引入依赖spring-cloud-starter-eureka、spring-cloud-starter-ribbon、spring-boot-starter-web,pom.xml如下:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.utour</groupId>
    <artifactId>service-ribbon</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>service-ribbon</name>
    <packaging>jar</packaging>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.M3</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</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>
        </repository>
    </repositories>

</project>

3. 通过@EnableEurekaClient 向服务中心注册,并且向程序的ioc注入一个bean: restTemplate;并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能,代码如下:

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import com.netflix.loadbalancer.RoundRobinRule;
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.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@EnableEurekaClient
@SpringBootApplication
public class ServiceRibbonApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceRibbonApplication.class, args);
    }

    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    /**
     *  负载均衡策略:不加这个Bean默认是轮询,RandomRule是随机访问。
     */
    //@Bean
    public IRule ribbonRule() {
        return new RandomRule();
    }

}

4. 配置文件application.yml如下:

server:
  port: 8764
eureka:
  client:
    service-url:
      #注册中心的地址
      defaultZone: http://localhost:8761/eureka/
spring:
  application:
    name: service-ribbon

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

import com.utour.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @Description
 * @Author wangxm
 * @Date 2019/10/23 17:16
 **/
@Service
public class TestServiceImpl implements TestService {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public String test() {
        return restTemplate.getForObject("http://EUREKA-CLIENT/test/come", String.class);
    }

}

6. 写一个TestController,在controller中用调用TestService 的方法,代码如下:

import com.utour.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description
 * @Author wangxm
 * @Date 2019/10/23 17:20
 **/
@RestController
public class TestController {

    @Autowired
    private TestService testService;

    @GetMapping("/hi")
    public String hi() {
        return testService.test();
    }

}

在浏览器上多次访问http://localhost:8764/hi,浏览器交替显示:

come on:8762
come on:8763

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

三、此时项目架构

  • 一个服务注册中心:eureka-server,端口为8761。
  • eureka-client工程跑了两个实例,端口分别为8762、8763,分别注册到服务注册中心eureka-server。
  • server-ribbon端口为8764,注册到eureka-server。
  • 当sercvice-ribbon通过restTemplate调用eureka-client的“/test/come”接口时,因为用ribbon进行了负载均衡,会轮流的调用eureka-client:8762和8763 两个端口的接口。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值