微服务精通之Ribbon原理解析

前言

       经过《微服务精通之Eureka原理解析》的学习,我们知道服务消费者可以从Eureka服务端获取到服务实例列表。获取到实例列表以后,按照寻常的做法,我们应该要实现一个负载均衡的逻辑,从实例列表中筛选出一个实例,然后调用该实例的方法。而Spring cloud通过Ribbon已经帮我们实现了这些功能。


一、Ribbon是什么?

       Spring Cloud Ribbon是一个基于HTTP和TCP的客户端负载均衡工具,它基于Netflix Ribbon实现。通过Spring Cloud的封装,可以让我们轻松地将面对服务的REST模块请求自动转换成客户端负载均衡的服务调用。

二、负载均衡是什么?

       这里引用百度百科来说明一下。

负载均衡,英文名称为Load Balance,其含义就是指将负载(工作任务)进行平衡、分摊到多个操作单元上进行运行,例如FTP服务器、Web服务器、企业核心应用服务器和其它主要任务服务器等,从而协同完成工作任务。

三、Ribbon原理解析

1.总体流程

在这里插入图片描述
流程说明:
       (1)服务提供者注册服务到Eureka服务端;
       (2)服务消费者的Eureka客户端定时从Eureka服务端获取实例列表;
       (3)Ribbon定时从Eureka客户端获取对应服务的实例列表;
       (4)Ribbon根据负载均衡规则获取到一个实例,然后调用这个实例的接口。

2.负载均衡器架构

在这里插入图片描述
       (1)负载均衡器在初始化的时候,会从Eureka获取一次实例列表;
       (2)负载均衡器在初始化的时候,会启动一个ServerListUpdater定时器,默认每10秒从Eureka同步一次实例列表;
       (3)在获取到实例列表以后,如果负载均衡器带有服务列表过滤器(ServerListFilter),要将实例列表通过服务列表过滤器(ServerListFilter)过滤一遍,获取到最终的实例列表;
       (4)负载均衡器在初始化的时候,会启动一个PingTask定时器,默认每30秒校验一下实例列表中的所有实例是否可用;
       (5)完成上述步骤后,我们会获取到一个可用的实例列表,当要进行接口调用的时候,负载均衡器会通过负载均衡规则(IRule)筛选出其中一个实例,以供调用。

3.负载均衡规则

       轮询策略:根据实例列表,逐个轮询调用。该策略为默认策略
       随机策略:根据实例列表,随机获取其中一个实例
       重试策略:在重试时间结束之前,使用轮询策略获取实例,若能获取到实例,则返回,否则继续轮询获取实例
       响应时间权重策略:根据实例平均响应时间划分区间,选择实例时,获取一个随机数,在哪个区间,就选择哪个实例
       最佳可用策略:过滤故障实例,并选择并发连接数最少的实例
       断言策略:使用google的Predicate进行实例过滤,然后再使用轮询策略
       可用过滤策略:先过滤掉故障的、并发请求数大于阈值的实例,然后再使用轮询策略

4.默认负载均衡器(区域识别负载均衡器)

均衡策略

       可用区域小于等于1时,使用父类负载均衡规则,否则使用区域筛选规则。

筛选可用区域规则

       (1)移除可用实例为0的区域;
       (2)移除故障率大于0.9999的区域;
       (3)如果所有区域没有符合上面2个条件,且平均负载均小于阈值(默认20%),则返回所有区域,否则随机剔除一个条件最差的区域。

5.服务列表过滤器

区域感知过滤器(ZoneAffinityServerListFilter)

       满足以下任一条件则不进行区域区分,否则使用本区域实例:
              (1)本区域实例故障率大于等于0.8
              (2)本区域实例平均负载大于等于0.6
              (3)本区域可用实例数量小于2

区域偏好过滤器(ZonePreferenceServerListFilter)

       区域偏好过滤器是区域感知过滤器的子过滤器,其过滤操作是基于区域感知过滤器的过滤规则。
       若区域感知过滤器过滤后的实例列表与原实例列表数据量一致,即区域感知过滤器未进行实例列表过滤,则遍历所有实例,返回本区域实例。
       注:此过滤器为默认过滤器。

服务列表子集过滤器(ServerListSubsetFilter)

       服务列表子集过滤器是区域感知过滤器的子过滤器,其过滤操作是基于区域感知过滤器的过滤规则。
       若区域感知过滤器过滤后的实例列表与原实例列表数据量一致,即区域感知过滤器未进行实例列表过滤,则按照如下规则进行处理:
              (1)剔除并发连接数到达上限的实例,默认并发连接数上限为0;
              (2)剔除失败数到达上限的实例,默认失败数上限为0;
              (3)若剩余实例数量大于目标实例数量(默认为20),则剔除多余实例,然后返回;
              (4)若剩余实例数量小于等于目标实例数量(默认为20),但是剔除实例数量小于剔除比例(默认为0.1),则剔除多余实例,然后返回。
       注:此过滤器非常适用于大规模服务器集群(上百或者更多)的系统。


四、Ribbon实战

1.创建Ribbon服务提供者

       注:若已看过《微服务精通之Eureka原理解析》,则此章节可跳过。

(1)创建名为service-hi的maven工程

(2)引入Eureka-client依赖

<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.hxq</groupId>
		<artifactId>spring-cloud-hxq</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>

	<artifactId>service-hi</artifactId>
	<name>service-hi</name>

	<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-eureka-client</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

       (1)Web依赖:spring-boot-starter-web;
       (2)Eureka-client依赖:spring-cloud-starter-netflix-eureka-client。

(3)创建启动类

package com.hxq;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 服务提供者
 * 
 * @author Administrator
 *
 */
@SpringBootApplication
@EnableEurekaClient
@RestController
public class ServiceHiApplication {

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

    /**
     * 服务端口
     */
    @Value("${server.port}")
    private String port;

    @RequestMapping("/hi")
    public String home(@RequestParam(value = "name", defaultValue = "hxq") String name) {
        return "hi " + name + " ,i am from port:" + port;
    }
}

       启动类要加上@EnableEurekaClient注解。

(4)创建application.yml配置文件

server:
    port: 9100
    
spring:
    application:
        name: service-hi

eureka:
    serviceUrl:
        defaultZone: http://localhost:8761/eureka/

       配置说明:
              server.port:Eureka客户端服务端口
              spring.application.name:应用名称,将会显示在Eureka界面的应用名称列。
              eureka.serviceUrl.defaultZone:Eureka服务器的地址,类型为HashMap,缺省的Key为 defaultZone;缺省的Value为 http://localhost:8761/eureka。如果服务注册中心为高可用集群时,多个注册中心地址以逗号分隔。

2.创建Ribbon消费者

(1)创建名为service-ribbon的maven工程

(2)引入Eureka-client和Ribbon依赖

<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.hxq</groupId>
		<artifactId>spring-cloud-hxq</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>

	<artifactId>service-ribbon</artifactId>
	<name>service-ribbon</name>

	<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-eureka-client</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
		</dependency>
	</dependencies>
</project>

       (1)Web依赖:spring-boot-starter-web;
       (2)Eureka-client依赖:spring-cloud-starter-netflix-eureka-client;
       (3)Ribbon依赖:spring-cloud-starter-netflix-ribbon。

(3)创建启动类

package com.hxq;

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;

/**
 * 服务消费者
 * 
 * @author Administrator
 *
 */
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class ServiceRibbonApplication {

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

    /**
     * 负载均衡器
     * 
     * @return
     */
    @LoadBalanced
    @Bean
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

       (1)启动类要加上@EnableEurekaClient注解和@EnableDiscoveryClient注解。
       (2)启动类中创建RestTemplate,用来调用service-hi的服务。

(4)创建一个测试接口

package com.hxq.controller;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.hxq.service.HelloService;

@RestController
public class HelloController {

    @Resource
    private HelloService helloService;
    
    @RequestMapping("/hi")
    public String hi(@RequestParam(value="name", defaultValue="hxq")String name) {
        return helloService.hiService(name);
    }
}
package com.hxq.service;

public interface HelloService {

    String hiService(String name);
}
package com.hxq.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.hxq.service.HelloService;

@Service("helloService")
public class HelloServiceImpl implements HelloService {

    @Resource
    private RestTemplate restTemplate;

    @Override
    public String hiService(String name) {
        return restTemplate.getForObject("http://SERVICE-HI/hi?name={1}", String.class, name);
    }
}

(5)创建application.yml配置文件

server:
    port: 9200
    
spring:
    application:
        name: service-ribbon

eureka:
    serviceUrl:
        defaultZone: http://localhost:8761/eureka/

       配置说明:
              server.port:Ribbon消费者服务端口
              eureka.serviceUrl.defaultZone:Eureka服务器的地址,类型为HashMap,缺省的Key为 defaultZone;缺省的Value为 http://localhost:8761/eureka。如果服务注册中心为高可用集群时,多个注册中心地址以逗号分隔。
              spring.application.name:应用名称,将会显示在Eureka界面的应用名称列。

3.服务验证

(1)启动service-hi服务

在这里插入图片描述

(2)启动service-ribbon服务

在这里插入图片描述

(3)调用测试接口

       在浏览器中输入http://localhost:9200/hi,如下图:
在这里插入图片描述
       可以看到接口返回service-hi服务的数据。

五、微服务精通系列文章

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

石头聊技术

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值