1.案例搭建
使用微服务架构的分布式系统,微服务之间通过网络通信。我们通过服务提供者与服务消费者来描述微服
务间的调用关系。
服务提供者:服务的被调用方,提供调用接口的一方
服务消费者:服务的调用方,依赖于其他服务的一方
我们以电商系统中常见的用户下单为例,用户向订单微服务发起一个购买的请求。在进行保存订单之前
需要调用商品微服务查询当前商品库存,单价等信息。在这种场景下,订单微服务就是一个服务消费
者,商品微服务就是一个服务提供者
2.1 数据库表
资料中提供了案例中所需要的数据库表与实体类
用户表
CREATE TABLE `tb_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(40) DEFAULT NULL COMMENT '用户名',
`password` varchar(40) DEFAULT NULL COMMENT '密码',
`age` int(3) DEFAULT NULL COMMENT '年龄',
`balance` decimal(10,2) DEFAULT NULL COMMENT '余额',
`address` varchar(80) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
商品表
CREATE TABLE `tb_product` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`product_name` varchar(40) DEFAULT NULL COMMENT '名称',
`status` int(2) DEFAULT NULL COMMENT '状态',
`price` decimal(10,2) DEFAULT NULL COMMENT '单价',
`product_desc` varchar(255) DEFAULT NULL COMMENT '描述',
`caption` varchar(255) DEFAULT NULL COMMENT '标题',
`inventory` int(11) DEFAULT NULL COMMENT '库存',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
订单表
CREATE TABLE `tb_order` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL COMMENT '用户id',
`product_id` int(11) DEFAULT NULL COMMENT '商品id',
`number` int(11) DEFAULT NULL COMMENT '数量',
`price` decimal(10,2) DEFAULT NULL COMMENT '单价',
`amount` decimal(10,2) DEFAULT NULL COMMENT '总额',
`product_name` varchar(40) DEFAULT NULL COMMENT '商品名',
`username` varchar(40) DEFAULT NULL COMMENT '用户名',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
2.2 搭建环境
(1)创建父工程shop_parent
在IDEA中创建父工程 shop_parent
并引入坐标
<?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>cn.itcast</groupId>
<artifactId>spring_cloud_demo</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</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.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
<scope>provided</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.3 搭建商品微服务
product的pom文件
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--引入EurekaClient-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
2.3.1 编写实体类
创建 cn.itcast.entity.Product 实体类,并配置
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.math.BigDecimal;
@Data
@Entity
@Table(name="tb_product")
public class Product {
@Id
private Long id;
private String productName;
private Integer status;
private BigDecimal price;
private String productDesc;
private String caption;
}
2.3.2 编写dao接口
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface ProductDao extends JpaRepository<Product,Long>, JpaSpecificationExecutor<Product> {
}
2.3.3 编写service层
public interface ProductService {
/**
* 根据id查询
*/
Product findById(Long id);
/**
* 保存
*/
void save(Product product);
/**
* 更新
*/
void update(Product product);
/**
* 删除
*/
void delete(Long id);
}
@Service
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductDao productDao;
@Override
public Product findById(Long id) {
return productDao.findById(id).get();
}
@Override
public void save(Product product) {
productDao.save(product);
}
@Override
public void update(Product product) {
productDao.save(product);
}
@Override
public void delete(Long id) {
productDao.deleteById(id);
}
}
2.3.4 编写web层
@RestController
@RequestMapping("/product")
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping("/{id}")
public Product findById(@PathVariable Long id) {
return productService.findById(id);
}
@PostMapping
public String save(@RequestBody Product product) {
productService.save(product);
return "保存成功";
}
@PutMapping("/{id}")
public String update(@RequestBody Product product) {
productService.update(product);
return "修改成功";
}
@DeleteMapping("/{id}")
public String delete(Long id) {
productService.delete(id);
return "删除成功";
}
}
controller中使用的@GetMapping是一个组合注解,相当与@RequestMapping(method=“get”)。
类似的注解还有@PostMapping,@PutMapping,@DeleteMapping
2.3.5 配置启动类
@SpringBootApplication(scanBasePackages="cn.itcast")
@EntityScan("cn.itcast.entity")
public class ProductApplication {
public static void main(String[] args) {
SpringApplication.run(ProductApplication.class, args);
}
}
2.3.6 配置yml文件
server:
port: 9001 #端口
spring:
application:
name: service-product #服务名称
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8
username: root
password: 123456
jpa:
database: MySQL
show-sql: true
open-in-view: true
2.3.7 测试
2.4 其他微服务
order的pom文件
<?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">
<parent>
<artifactId>spring_cloud_demo</artifactId>
<groupId>cn.itcast</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>Order</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
2.5 服务调用
前文已经编写了基础的微服务,在用户下单时需要调用商品微服务获取商品数据。那应该怎么做
呢?总人皆知商品微服务提供了供人调用的HTTP接口。所以可以再下定单的时候使用http请求的相关
工具类完成,如常见的HttpClient,OkHttp,当然也可以使用Spring提供的RestTemplate
2.5.1 RestTemplate介绍
- Spring框架提供的RestTemplate类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统
一了RESTful的标准,封装了http链接, 我们只需要传入url及返回值类型即可。相较于之前常用的
HttpClient,RestTemplate是一种更优雅的调用RESTful服务的方式。 - 在Spring应用程序中访问第三方REST服务与使用Spring RestTemplate类有关。RestTemplate类的设计
原则与许多其他Spring 模板类(例如JdbcTemplate、JmsTemplate)相同,为执行复杂任务提供了一种具
有默认行为的简化方法。 - RestTemplate默认依赖JDK提供http连接的能力(HttpURLConnection),如果有需要的话也可以通过
setRequestFactory方法替换为例如 Apache HttpComponents、Netty或OkHttp等其它HTTP library。 - 考虑到RestTemplate类是为调用REST服务而设计的,因此它的主要方法与REST的基础紧密相连就不足
为奇了,后者是HTTP协议的方法:HEAD、GET、POST、PUT、DELETE和OPTIONS。例如,
RestTemplate类具有headForHeaders()、getForObject()、postForObject()、put()和delete()等方法。
2.5.2 RestTemplate方法介绍
2.5.3 通过RestTemplate调用微服务
(1) 在 shop_service_order工程中ProductApplication启动类 中配置RestTemplate
@SpringBootApplication
@EntityScan("cn.itcast.order.entity")
public class OrderApplication {
/**
* 使用spring提供的RestTemplate发送http请求到商品服务
* 1.创建RestTemplate对象交给容器管理
* 2.在使用的时候,调用其方法完成操作 (getXX,postxxx)
* *
*/
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class,args);
}
}
(2) 编写下订单方法
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/{id}")
public String order(Integer num) {
//通过restTemplate调用商品微服务
Product object =
restTemplate.getForObject("http://127.0.0.1:9001/product/2", Product.class);
System.out.println(object);
return "操作成功";
}
}
测试
2.5.4 硬编码存在的问题
至此已经可以通过RestTemplate调用商品微服务的RESTFul API接口。但是我们把提供者的网络地址
(ip,端口)等硬编码到了代码中,这种做法存在许多问题:
- 应用场景有局限
- 无法动态调整
那么应该怎么解决呢,就需要通过注册中心动态的对服务注册和服务发现
3 服务注册Eureka基础
3.1 微服务的注册中心
注册中心可以说是微服务架构中的”通讯录“,它记录了服务和服务地址的映射关系。在分布式架构中,
服务会注册到这里,当服务需要调用其它服务时,就这里找到服务的地址,进行调用。
3.1.1 注册中心的主要作用
服务注册中心(下称注册中心)是微服务架构非常重要的一个组件,在微服务架构里主要起到了协调者
的一个作用。注册中心一般包含如下几个功能:
- 服务发现:
服务注册/反注册:保存服务提供者和服务调用者的信息
服务订阅/取消订阅:服务调用者订阅服务提供者的信息,最好有实时推送的功能
服务路由(可选):具有筛选整合服务提供者的能力。 - 服务配置:
配置订阅:服务提供者和服务调用者订阅微服务相关的配置
配置下发:主动将配置推送给服务提供者和服务调用者 - 服务健康检测
检测服务提供者的健康情况
3.1.2 常见的注册中心
3.2 Eureka的概述
3.2.1 Eureka的基础知识
Eureka是Netflix开发的服务发现框架,SpringCloud将它集成在自己的子项目spring-cloud-netflix中,
实现SpringCloud的服务发现功能。
上图简要描述了Eureka的基本架构,由3个角色组成:
1、Eureka Server
提供服务注册和发现
2、Service Provider
服务提供方
将自身服务注册到Eureka,从而使服务消费方能够找到
3、Service Consumer
服务消费方
从Eureka获取注册服务列表,从而能够消费服务
3.2.2 Eureka的交互流程与原理
图是来自Eureka官方的架构图,大致描述了Eureka集群的工作过程。图中包含的组件非常多,可能比
较难以理解,我们用通俗易懂的语言解释一下:
- Application Service 相当于本书中的服务提供者,Application Client相当于服务消费者;
- Make Remote Call,可以简单理解为调用RESTful API;
- us-east-1c、us-east-1d等都是zone,它们都属于us-east-1这个region;
由图可知,Eureka包含两个组件:Eureka Server 和 Eureka Client,它们的作用如下:
- Eureka Client是一个Java客户端,用于简化与Eureka Server的交互;
- Eureka Server提供服务发现的能力,各个微服务启动时,会通过Eureka Client向Eureka Server
- 进行注册自己的信息(例如网络信息),Eureka Server会存储该服务的信息;
- 微服务启动后,会周期性地向Eureka Server发送心跳(默认周期为30秒)以续约自己的信息。如
果Eureka Server在一定时间内没有接收到某个微服务节点的心跳,Eureka Server将会注销该微服
务节点(默认90秒); - 每个Eureka Server同时也是Eureka Client,多个Eureka Server之间通过复制的方式完成服务注
册表的同步; - Eureka Client会缓存Eureka Server中的信息。即使所有的Eureka Server节点都宕掉,服务消费
者依然可以使用缓存中的信息找到服务提供者。
综上,Eureka通过心跳检测、健康检查和客户端缓存等机制,提高了系统的灵活性、可伸缩性和可用
性。
3.3 搭建Eureka注册中心
3.3.1 搭建Eureka服务中心
(1) 创建eureka_server子模块
(2) 引入maven坐标
<?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">
<parent>
<artifactId>spring_cloud_demo</artifactId>
<groupId>cn.itcast</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>eureka_server</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>
</project>
(3) 配置application.yml
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${
eureka.instance.hostname}:${
server.port}/eureka/
registerWithEureka: 是否将自己注册到Eureka服务中,本身就是所有无需注册
fetchRegistry :是否从Eureka中获取注册信息
serviceUrlEureka: 客户端与Eureka服务端进行交互的地址
(4) 配置启动类
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
EnableEurekaServer : 激活Eureka Server端配置
3.3.2 服务注册中心管理后台
打开浏览器访问http://localhost8761即可进入EurekaServer内置的管理控制台,显示效果如下
3.4 服务注册到Eureka注册中心
3.4.1 商品服务注册
(1) 商品模块中引入坐标
在 shop_service_product 的pom文件中添加eureka client的相关坐标
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
(2) 配置application.yml文件
在工程的 application.yml 中添加Eureka Server的主机地址
eureka:
client:
serviceUrl: # eureka server的路径
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true #使用ip注册
(3) 修改启动类添加服务注册注解
@SpringBootApplication
//@EnableDiscoveryClient
//@EnableEurekaClient
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class, args);
}
}
从Spring Cloud Edgware版本开始, @EnableDiscoveryClient 或
@EnableEurekaClient 可 省略。只需加上相关依赖,并进行相应配置,即可将微服务注册到服务发现组件上。
3.5 Eureka中的自我保护
微服务第一次注册成功之后,每30秒会发送一次心跳将服务的实例信息注册到注册中心。通知 Eureka
Server 该实例仍然存在。如果超过90秒没有发送更新,则服务器将从注册信息中将此服务移除。
Eureka Server在运行期间,会统计心跳失败的比例在15分钟之内是否低于85%,如果出现低于的情况
(在单机调试的时候很容易满足,实际在生产环境上通常是由于网络不稳定导致),Eureka Server会
将当前的实例注册信息保护起来,同时提示这个警告。保护模式主要用于一组客户端和Eureka Server
之间存在网络分区场景下的保护。一旦进入保护模式,Eureka Server将会尝试保护其服务注册表中的
信息,不再删除服务注册表中的数据(也就是不会注销任何微服务)
验证完自我保护机制开启后,并不会马上呈现到web上,而是默认需等待 5 分钟(可以通过
eureka.server.wait-time-in-ms-when-sync-empty 配置),即 5 分钟后你会看到下面的提示信息:
如果关闭自我保护
通过设置 eureka.enableSelfPreservation=false
来关闭自我保护功能。
3.6 Eureka中的元数据
Eureka的元数据有两种:标准元数据和自定义元数据。
- 标准元数据:主机名、IP地址、端口号、状态页和健康检查等信息,这些信息都会被发布在服务注
册表中,用于服务之间的调用。 - 自定义元数据:可以使用eureka.instance.metadata-map配置,符合KEY/VALUE的存储格式。这
些元数据可以在远程客户端中访问。
在程序中可以使用DiscoveryClient 获取指定微服务的所有元数据信息
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class T {
@Autowired(required = false)
private ProductDao dao;
@Test
public void setDao(){
List<Product> all = dao.findAll();
}
@Test
public void d(){
dao.findAll().forEach(System.out::println);
}
@Autowired(required = false)
private DiscoveryClient discoveryClient;
@Test
public void test(){
System.out.println("---------------这里是分割线---------------");
List<ServiceInstance> instances = discoveryClient.getInstances("SERVICE-PRODUCT");
for (ServiceInstance instance : instances) {
System.out.println(instance);
}
System.out.println("---------------这里是分割线---------------");
}
}
4 服务注册Eureka高级
5 Eureka替换方案Consul
5.1 Eureka闭源的影响
5.1.2 Eureka的替换方案
Zookeeper
ZooKeeper是一个分布式的,开放源码的分布式应用程序协调服务,是Google的Chubby一个开源的实
现,是Hadoop和Hbase的重要组件。它是一个为分布式应用提供一致性服务的软件,提供的功能包
括:配置维护、域名服务、分布式同步、组服务等。
Consul
consul是近几年比较流行的服务发现工具,工作中用到,简单了解一下。consul的三个主要应用场景:
服务发现、服务隔离、服务配置。
Nacos
Nacos 是阿里巴巴推出来的一个新开源项目,这是一个更易于构建云原生应用的动态服务发现、配置管
理和服务管理平台。Nacos 致力于帮助您发现、配置和管理微服务。Nacos 提供了一组简单易用的特性
集,帮助您快速实现动态服务发现、服务配置、服务元数据及流量管理。Nacos 帮助您更敏捷和容易地
构建、交付和管理微服务平台。 Nacos 是构建以“服务”为中心的现代应用架构 (例如微服务范式、云原
生范式) 的服务基础设施。
5.2 什么是consul
5.3 consul的基本使用
5.4 基于consul的服务注册
5.4.1 案例准备
(1)复制一份新的工程进行配置
拷贝一份新的工程,起名为 shop_consul_parent ,并导入相关的子模块
(2)修改微服务的相关pom文件
修改每个微服务的pom文件,添加SpringCloud提供的基于Consul的依赖
<!--SpringCloud提供的基于Consul的服务发现-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<!--actuator用于心跳检查-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
其中 spring-cloud-starter-consul-discovery
是SpringCloud提供的对consul支持的相关依赖。
spring-boot-starter-actuator
适用于完成心跳检测响应的相关依赖。
5.4.2 配置服务注册
修改每个微服务的application.yml配置文件,添加consul服务发现的相关配置信息
spring:
...省略
cloud:
consul: #consul相关配置
host: 192.168.74.101 #ConsulServer请求地址
port: 8500 #ConsulServer端口
discovery:
#是否注册
register: true
#实例ID
instance-id: ${
spring.application.name}-1
#服务实例名称
service-name: ${
spring.application.name}
#服务实例端口
port: ${
server.port}
#健康检查路径
healthCheckPath: /actuator/health
#健康检查时间间隔
healthCheckInterval: 15s
#开启ip地址注册
prefer-ip-address: true
#实例的请求ip
ip-address: ${
spring.cloud.client.ip-address}
5.4.3 在控制台中查看服务列表
打开ConsulServer的管理控制台,可以发现三个微服务已经全部注册到Consul中了。
5.5 基于consul的服务发现
由于SpringCloud对Consul进行了封装。对于在消费者端获取服务提供者信息和Eureka是一致的。同样
使用 DiscoveryClient 完成调用获取微服务实例信息
6 服务调用Ribbon入门
经过以上的学习,已经实现了服务的注册和服务发现。当启动某个服务的时候,可以通过HTTP的形式
将信息注册到注册中心,并且可以通过SpringCloud提供的工具获取注册中心的服务列表。但是服务之
间的调用还存在很多的问题,如何更加方便的调用微服务,多个微服务的提供者如何选择,如何负载均
衡等。
6.2 Ribbon概述
6.2.1 什么是Ribbon
是 Netflixfa 发布的一个负载均衡器,有助于控制 HTTP 和 TCP客户端行为。在 SpringCloud 中,
Eureka一般配合Ribbon进行使用,Ribbon提供了客户端负载均衡的功能,Ribbon利用从Eureka中读
取到的服务信息,在调用服务节点提供的服务时,会合理的进行负载。
在SpringCloud中可以将注册中心和Ribbon配合使用,Ribbon自动的从注册中心中获取服务提供者的
列表信息,并基于内置的负载均衡算法,请求服务
6.2.2 Ribbon的主要作用
(1)服务调用
基于Ribbon实现服务调用, 是通过拉取到的所有服务列表组成(服务名-请求路径的)映射关系。借助
RestTemplate 最终进行调用
(2)负载均衡
当有多个服务提供者时,Ribbon可以根据负载均衡的算法自动的选择需要调用的服务地址
7 服务调用Ribbon高级
7.1 负载均衡概述
7.1.1 什么是负载均衡
在搭建网站时,如果单节点的 web服务性能和可靠性都无法达到要求;或者是在使用外网服务时,经常
担心被人攻破,一不小心就会有打开外网端口的情况,通常这个时候加入负载均衡就能有效解决服务问
题。
负载均衡是一种基础的网络服务,其原理是通过运行在前面的负载均衡服务,按照指定的负载均衡算
法,将流量分配到后端服务集群上,从而为系统提供并行扩展的能力。
负载均衡的应用场景包括流量包、转发规则以及后端服务,由于该服务有内外网个例、健康检查等功
能,能够有效提供系统的安全性和可用性。