SpringCloud基础第一部分

今日内容

  • 系统架构演变
  • 服务调用方式
  • Spring的RestTemplate
  • SpringCloud
  • Eureka
  • Ribbon
  • Hystrix

第一章 系统架构演变

随着互联网的发展,网站应用的规模不断扩大。需求的激增,带来的是技术上的压力。系统架构也因此也不断的演进、升级、迭代。从单一应用,到垂直拆分,到分布式服务,到SOA,以及现在火热的微服务架构,还有在Google带领下来势汹涌的Service Mesh。我们到底是该乘坐微服务的船只驶向远方,还是偏安一隅得过且过?

其实生活不止眼前的苟且,还有诗和远方。所以我们今天就回顾历史,看一看系统架构演变的历程;把握现在,学习现在最火的技术架构;展望未来,争取成为一名优秀的Java工程师。

1. 集中式架构(单体架构)

当网站流量很小时,只需一个应用,将所有功能都部署在一起,以减少部署节点和成本。此时,用于简化增删改查工作量的数据访问框架(ORM)是影响项目开发的关键。

1545912768292

存在的问题:

  • 代码耦合,开发维护困难
  • 无法针对不同模块进行针对性优化
  • 无法水平扩展
  • 单点容错率低,并发能力差

2.垂直拆分

当访问量逐渐增大,单一应用无法满足需求,此时为了应对更高的并发和业务需求,我们根据业务功能对系统进行拆分:

1545912974097

优点:

  • 系统拆分实现了流量分担,解决了并发问题
  • 可以针对不同模块进行优化
  • 方便水平扩展,负载均衡,容错率提高

缺点:

  • 系统间相互独立,会有很多重复开发工作,影响开发效率

3.分布式服务

当垂直应用越来越多,应用之间交互不可避免,将核心业务抽取出来,作为独立的服务,逐渐形成稳定的服务中心,使前端应用能更快速的响应多变的市场需求。此时,用于提高业务复用及整合的分布式调用是关键。

1545913905548

优点:

  • 将基础服务进行了抽取,系统间相互调用,提高了代码复用和开发效率

缺点:

  • 系统间耦合度变高,调用关系错综复杂,难以维护

4.服务治理架构(SOA)

SOA :面向服务的架构

当服务越来越多,容量的评估,小服务资源的浪费等问题逐渐显现,此时需增加一个调度中心基于访问压力实时管理集群容量,提高集群利用率。此时,用于提高机器利用率的资源调度和治理中心(SOA)是关键

1525530804753

以前出现了什么问题?

  • 服务越来越多,需要管理每个服务的地址
  • 调用关系错综复杂,难以理清依赖关系
  • 服务过多,服务状态难以管理,无法根据服务情况动态管理

服务治理要做什么?

  • 服务注册中心,实现服务自动注册和发现,无需人为记录服务地址
  • 服务自动订阅,服务列表自动推送,服务调用透明化,无需关心依赖关系
  • 动态监控服务状态监控报告,人为控制服务状态

缺点:

  • 服务间会有依赖关系,一旦某个环节出错会影响较大
  • 服务关系复杂,运维、测试部署困难,不符合DevOps思想

5.微服务

前面说的SOA,英文翻译过来是面向服务。微服务,似乎也是服务,都是对系统进行拆分。因此两者非常容易混淆,但其实缺有一些差别:

60436593400

微服务的特点:

  • 单一职责:微服务中每一个服务都对应唯一的业务能力,做到单一职责
  • 微:微服务的服务拆分粒度很小,例如一个用户管理就可以作为一个服务。每个服务虽小,但“五脏俱全”。
  • 面向服务:面向服务是说每个服务都要对外暴露Rest风格服务接口API。并不关心服务的技术实现,做到与平台和语言无关,也不限定用什么技术实现,只要提供Rest的接口即可。
  • 自治:自治是说服务间互相独立,互不干扰
    • 团队独立:每个服务都是一个独立的开发团队,人数不能过多。
    • 技术独立:因为是面向服务,提供Rest接口,使用什么技术没有别人干涉
    • 前后端分离:采用前后端分离开发,提供统一Rest接口,后端不用再为PC、移动段开发不同接口
    • 数据库分离:每个服务都使用自己的数据源
    • 部署独立,服务间虽然有调用,但要做到服务重启不影响其它服务。有利于持续集成和持续交付。每个服务都是独立的组件,可复用,可替换,降低耦合,易维护

微服务结构图:

1526860071166

第二章 服务调用方式

1.RPC和HTTP

无论是微服务还是SOA,都面临着服务间的远程调用。那么服务间的远程调用方式有哪些呢?

常见的远程调用方式有以下2种:

  • RPC:Remote Produce Call远程过程调用,类似的还有RMI(remote method invoke)。自定义数据格式,基于原生TCP通信,速度快,效率高。早期的webservice,现在热门的dubbo,都是RPC的典型代表.

  • Http:http其实是一种网络传输协议,基于TCP,规定了数据传输的格式。现在客户端浏览器与服务端通信基本都是采用Http协议,也可以用来进行远程服务调用。缺点是消息封装臃肿,优势是对服务的提供和调用方没有任何技术限定,自由灵活,更符合微服务理念。

    现在热门的Rest风格,就可以通过http协议来实现。

如果你们公司全部采用Java技术栈,那么使用Dubbo作为微服务架构是一个不错的选择。

相反,如果公司的技术栈多样化,而且你更青睐Spring家族,那么SpringCloud搭建微服务是不二之选。在我们的项目中,我们会选择SpringCloud套件,因此我们会使用Http方式来实现服务间调用。

2.Http客户端工具

既然微服务选择了Http,那么我们就需要考虑自己来实现对请求和响应的处理。不过开源世界已经有很多的http客户端工具,能够帮助我们做这些事情,例如:

  • HttpClient
  • OKHttp
  • URLConnection

接下来,不过这些不同的客户端,API各不相同,都是通过java技术模拟浏览器发请求。

第三章 Spring的RestTemplate

Spring提供了一个RestTemplate模板工具类,对基于Http的客户端进行了封装,并且实现了对象与json的序列化和反序列化,非常方便。RestTemplate并没有限定Http的客户端类型,而是进行了抽象,目前常用的3种都有支持:

  • HttpClient
  • OkHttp
  • JDK原生的URLConnection(默认的)

我们导入课前资料提供的demo工程:

首先在项目中注册一个RestTemplate对象,可以在启动类位置注册:

1@SpringBootApplication 2public class HttpDemoApplication { 3 4 public static void main(String[] args) { 5 SpringApplication.run(HttpDemoApplication.class, args); 6 } 7 8 @Bean 9 public RestTemplate restTemplate() { 10 RestTemplate restTemplate = new RestTemplate(); 11 StringHttpMessageConverter messageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8")); 12// 修改默认的字符集 默认是的iso-8859-1 13 restTemplate.getMessageConverters().add(1,messageConverter); 14 return restTemplate; 15 } 16 17}

在测试类中直接@Autowired注入:

1package cn.itcast.test; 2 3import cn.itcast.HttpDemoApplication; 4import cn.itcast.pojo.User; 5import org.junit.Test; 6import org.junit.runner.RunWith; 7import org.springframework.beans.factory.annotation.Autowired; 8import org.springframework.boot.test.context.SpringBootTest; 9import org.springframework.test.context.junit4.SpringRunner; 10import org.springframework.web.client.RestTemplate; 11 12@RunWith(SpringRunner.class) 13@SpringBootTest(classes = HttpDemoApplication.class) 14public class HttpDemoApplicationTests { 15 16 @Autowired 17 private RestTemplate restTemplate; 18 19 @Test 20 public void httpGet() { 21 User user = this.restTemplate.getForObject("http://localhost/findById/8", User.class); 22 System.out.println(user); 23 } 24}
  • 通过RestTemplate的getForObject()方法,传递url地址及实体类的字节码,RestTemplate会自动发起请求,接收响应,并且帮我们对响应结果进行反序列化。

学习完了Http客户端工具,接下来就可以正式学习微服务了。

第四章 初识SpringCloud

微服务是一种架构方式,最终肯定需要技术架构去实施。

微服务的实现方式很多,但是最火的莫过于Spring Cloud了。为什么?

  • 后台硬:作为Spring家族的一员,有整个Spring全家桶靠山,背景十分强大。
  • 技术强:Spring作为Java领域的前辈,可以说是功力深厚。有强力的技术团队支撑,一般人还真比不了
  • 群众基础好:可以说大多数程序员的成长都伴随着Spring框架,试问:现在有几家公司开发不用Spring?SpringCloud与Spring的各个框架无缝整合,对大家来说一切都是熟悉的配方,熟悉的味道。
  • 使用方便:相信大家都体会到了SpringBoot给我们开发带来的便利,而SpringCloud完全支持SpringBoot的开发,用很少的配置就能完成微服务框架的搭建

1.简介

SpringCloud是Spring旗下的项目之一,官网地址:http://projects.spring.io/spring-cloud/

Spring最擅长的就是集成,把世界上最好的框架拿过来,集成到自己的项目中。

SpringCloud也是一样,它将现在非常流行的一些技术整合到一起,实现了诸如:配置管理,服务发现,智能路由,负载均衡,熔断器,控制总线,集群状态等等功能。其主要涉及的组件包括:

Netflix:

  • Eureka:注册中心
  • Zuul:服务网关
  • Ribbon:负载均衡
  • Feign:服务调用
  • Hystrix:熔断器

以上只是其中一部分,架构图:

1525575656796

2.版本

SpringCloud的版本命名比较特殊,因为它不是一个组件,而是许多组件的集合,它的命名是以A到Z的为首字母的一些单词(其实是伦敦地铁站的名字)组成:

image-20201103175533672

其中包含的组件,也都有各自的版本,如下表:

Component

Edgware.SR6

Greenwich.SR2

Greenwich.BUILD-SNAPSHOT

spring-cloud-aws

1.2.4.RELEASE

2.1.2.RELEASE

2.1.3.BUILD-SNAPSHOT

spring-cloud-bus

1.3.4.RELEASE

2.1.2.RELEASE

2.1.3.BUILD-SNAPSHOT

spring-cloud-cli

1.4.1.RELEASE

2.0.0.RELEASE

2.0.1.BUILD-SNAPSHOT

spring-cloud-commons

1.3.6.RELEASE

2.1.2.RELEASE

2.1.3.BUILD-SNAPSHOT

spring-cloud-contract

1.2.7.RELEASE

2.1.2.RELEASE

2.1.3.BUILD-SNAPSHOT

spring-cloud-config

1.4.7.RELEASE

2.1.3.RELEASE

2.1.4.BUILD-SNAPSHOT

spring-cloud-netflix

1.4.7.RELEASE

2.1.2.RELEASE

2.1.3.BUILD-SNAPSHOT

spring-cloud-security

1.2.4.RELEASE

2.1.3.RELEASE

2.1.4.BUILD-SNAPSHOT

spring-cloud-cloudfoundry

1.1.3.RELEASE

2.1.2.RELEASE

2.1.3.BUILD-SNAPSHOT

spring-cloud-consul

1.3.6.RELEASE

2.1.2.RELEASE

2.1.3.BUILD-SNAPSHOT

spring-cloud-sleuth

1.3.6.RELEASE

2.1.1.RELEASE

2.1.2.BUILD-SNAPSHOT

spring-cloud-stream

Ditmars.SR5

Fishtown.SR3

Fishtown.BUILD-SNAPSHOT

spring-cloud-zookeeper

1.2.3.RELEASE

2.1.2.RELEASE

2.1.3.BUILD-SNAPSHOT

spring-boot

1.5.21.RELEASE

2.1.5.RELEASE

2.1.8.BUILD-SNAPSHOT

spring-cloud-task

1.2.4.RELEASE

2.1.2.RELEASE

2.1.3.BUILD-SNAPSHOT

spring-cloud-vault

1.1.3.RELEASE

2.1.2.RELEASE

2.1.3.BUILD-SNAPSHOT

spring-cloud-gateway

1.0.3.RELEASE

2.1.2.RELEASE

2.1.3.BUILD-SNAPSHOT

spring-cloud-openfeign

 

2.1.2.RELEASE

2.1.3.BUILD-SNAPSHOT

spring-cloud-function

1.0.2.RELEASE

2.0.2.RELEASE

2.0.3.BUILD-SNAPSHOT

注意:SpringCloud和springboot版本的关系

Release Train

Boot Version

Hoxton

2.2.x

Greenwich

2.1.x

Finchley

2.0.x

Edgware

1.5.x

Dalston

1.5.x

接下来,我们就一一学习SpringCloud中的重要组件。

第五章 微服务场景模拟

首先,我们需要模拟一个服务调用的场景。方便后面学习微服务架构

1.创建父工程

微服务中需要同时创建多个项目,为了方便课堂演示,我们先创建一个父工程,然后后续的工程都以这个工程为父,实现maven的聚合。这样可以在一个窗口看到所有工程,方便我们讲解。**在实际开发中,应该是每个微服务独立一个工程。

image-20201103175640601

编写项目信息:

编写保存位置:

然后将Pom修改成这样:

1<?xml version="1.0" encoding="UTF-8"?> 2<project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>cn.itcast.demo</groupId> 8 <artifactId>cloud-demo</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 <packaging>pom</packaging> 11 12 <parent> 13 <groupId>org.springframework.boot</groupId> 14 <artifactId>spring-boot-starter-parent</artifactId> 15 <version>2.1.3.RELEASE</version> 16 </parent> 17 18 <properties> 19 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 20 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 21 <java.version>1.8</java.version> 22 <spring-cloud.version>Greenwich.SR1</spring-cloud.version> 23 <mapper.starter.version>2.1.4</mapper.starter.version> 24 <mysql.version>5.1.47</mysql.version> 25 <pageHelper.starter.version>1.2.5</pageHelper.starter.version> 26 </properties> 27 28 <dependencyManagement> 29 <dependencies> 30 <!-- springCloud --> 31 <dependency> 32 <groupId>org.springframework.cloud</groupId> 33 <artifactId>spring-cloud-dependencies</artifactId> 34 <version>${spring-cloud.version}</version> 35 <type>pom</type> 36 <scope>import</scope> 37 </dependency> 38 <!-- 通用Mapper启动器 --> 39 <dependency> 40 <groupId>tk.mybatis</groupId> 41 <artifactId>mapper-spring-boot-starter</artifactId> 42 <version>${mapper.starter.version}</version> 43 </dependency> 44 <!-- mysql驱动 --> 45 <dependency> 46 <groupId>mysql</groupId> 47 <artifactId>mysql-connector-java</artifactId> 48 <version>${mysql.version}</version> 49 </dependency> 50 </dependencies> 51 </dependencyManagement> 52 <dependencies> 53 <dependency> 54 <groupId>org.projectlombok</groupId> 55 <artifactId>lombok</artifactId> 56 </dependency> 57 </dependencies> 58 59 <build> 60 <plugins> 61 <plugin> 62 <groupId>org.springframework.boot</groupId> 63 <artifactId>spring-boot-maven-plugin</artifactId> 64 </plugin> 65 </plugins> 66 </build> 67</project>

这里已经对大部分要用到的依赖的版本进行了 管理,方便后续使用

2.服务提供者

我们新建一个项目,对外提供查询用户的服务。

2.1.创建module

填写module信息:

注意,子模块要在父工程的下级目录:

2.2.依赖

1<?xml version="1.0" encoding="UTF-8"?> 2<project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <parent> 6 <artifactId>cloud-demo</artifactId> 7 <groupId>cn.itcast.demo</groupId> 8 <version>1.0-SNAPSHOT</version> 9 </parent> 10 <modelVersion>4.0.0</modelVersion> 11 12 <artifactId>user-service</artifactId> 13 <version>1.0-SNAPSHOT</version> 14 15 <dependencies> 16 <dependency> 17 <groupId>org.springframework.boot</groupId> 18 <artifactId>spring-boot-starter-web</artifactId> 19 </dependency> 20 <dependency> 21 <groupId>mysql</groupId> 22 <artifactId>mysql-connector-java</artifactId> 23 </dependency> 24 <dependency> 25 <groupId>tk.mybatis</groupId> 26 <artifactId>mapper-spring-boot-starter</artifactId> 27 </dependency> 28 </dependencies> 29</project>

项目结构:

2.3. 编写代码

属性文件,这里我们采用了yml语法,而不是properties:

1server: 2 port: 8081 3spring: 4 datasource: 5 driver-class-name: com.mysql.jdbc.Driver 6 url: jdbc:mysql:///tb_user 7 username: root 8 password: root

启动类:

1package cn.itcast; 2import org.springframework.boot.SpringApplication; 3import org.springframework.boot.autoconfigure.SpringBootApplication; 4/** 5 * @description: 6 * @author: mryhl 7 * @date: Created in 2020/11/3 18:06 8 * @version: 1.0 9 */ 10@SpringBootApplication 11public class UserServiceApplication { 12 public static void main(String[] args) { 13 SpringApplication.run(UserServiceApplication.class,args); 14 } 15}

实体类:

1package cn.itcast.pojo; 2 3import lombok.Data; 4import tk.mybatis.mapper.annotation.KeySql; 5 6import javax.persistence.Id; 7import javax.persistence.Table; 8import java.util.Date; 9 10/** 11 * @description: 12 * @author: mryhl 13 * @date: Created in 2020/11/3 18:09 14 * @version: 1.0 15 */ 16@Table(name = "tb_user") 17@Data 18public class User { 19 @Id 20 @KeySql(useGeneratedKeys = true) 21 private Long id; 22 // 用户名 23 private String userName; 24 // 密码 25 private String password; 26 // 姓名 27 private String name; 28 // 年龄 29 private Integer age; 30 // 性别,1男性,2女性 31 32 private Integer sex; 33 // 出生日期 34 private Date birthday; 35 // 创建时间 36 private Date created; 37 // 更新时间 38 private Date updated; 39 // 备注 40 private String note; 41}

mapper:

1package cn.itcast.mapper; 2import cn.itcast.pojo.User; 3import tk.mybatis.mapper.common.Mapper; 4/** 5 * @description: 6 * @author: mryhl 7 * @date: Created in 2020/11/3 18:11 8 * @version: 1.0 9 */ 10public interface UserMapper extends Mapper<User> { 11}

Service:

1@Service 2public class UserService { 3 4 @Autowired 5 private UserMapper userMapper; 6 7 public User findByById(Long id) { 8 return userMapper.selectByPrimaryKey(id); 9 } 10}

添加一个对外查询的接口:

1package cn.itcast.controller; 2 3import cn.itcast.pojo.User; 4import cn.itcast.service.UserService; 5import org.springframework.beans.factory.annotation.Autowired; 6import org.springframework.web.bind.annotation.GetMapping; 7import org.springframework.web.bind.annotation.PathVariable; 8import org.springframework.web.bind.annotation.RequestMapping; 9import org.springframework.web.bind.annotation.RestController; 10 11/** 12 * @description: 13 * @author: mryhl 14 * @date: Created in 2020/11/3 19:33 15 * @version: 1.0 16 */ 17@RestController 18@RequestMapping("user") 19public class UserController { 20 @Autowired 21 private UserService userService; 22 23 @GetMapping("/{id}") 24 public User queryById(@PathVariable("id") Integer id){ 25 return userService.findById(id); 26 } 27}

项目结构:

2.4. 启动并测试:

启动项目,访问接口:http://localhost:8081/user/7

3.服务调用者

3.1.创建工程

与上面类似,这里不再赘述,需要注意的是,我们调用user-service的功能,因此不需要mybatis相关依赖了。

image-20201103193821567

pom:

1<?xml version="1.0" encoding="UTF-8"?> 2<project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <parent> 6 <artifactId>springcloud_demo</artifactId> 7 <groupId>cn.itcast</groupId> 8 <version>1.0-SNAPSHOT</version> 9 </parent> 10 <modelVersion>4.0.0</modelVersion> 11 12 <artifactId>consumer_demo</artifactId> 13 14 <dependencies> 15 <dependency> 16 <groupId>org.springframework.boot</groupId> 17 <artifactId>spring-boot-starter-web</artifactId> 18 </dependency> 19 </dependencies> 20</project>

3.2.编写代码

首先在启动类中注册RestTemplate

1package cn.itcast; 2 3import org.springframework.boot.SpringApplication; 4import org.springframework.boot.autoconfigure.SpringBootApplication; 5import org.springframework.context.annotation.Bean; 6import org.springframework.web.client.RestTemplate; 7 8/** 9 * @description: 10 * @author: mryhl 11 * @date: Created in 2020/11/3 19:40 12 * @version: 1.0 13 */ 14@SpringBootApplication 15public class ConsumerApplication { 16 @Bean 17 public RestTemplate restTemplate(){ 18 return new RestTemplate(); 19 } 20 21 public static void main(String[] args) { 22 SpringApplication.run(ConsumerApplication.class,args); 23 } 24}

实体类:

1@Data 2public class User { 3 4 private Long id; 5 6 private String userName; // 用户名 7 8 private String password; // 密码 9 10 private String name;// 姓名 11 12 private Integer age;// 年龄 13 14 private Integer sex;// 性别,1男性,2女性 15 16 private Date birthday;// 出生日期 17 18 private Date created;// 创建时间 19 20 private Date updated;// 更新时间 21 22 private String note;// 备注 23 24}

编写controller,在controller中直接调用RestTemplate,远程访问user-service的服务接口:

1@RestController 2@RequestMapping("consumer") 3public class ConsumerController { 4 5 @Autowired 6 private RestTemplate restTemplate; 7 8 @GetMapping("{id}") 9 public User queryById(@PathVariable("id") Long id){ 10 String url = "http://localhost:8081/user/" + id; 11 User user = restTemplate.getForObject(url, User.class); 12 return user; 13 } 14}

项目结构:

3.3.启动测试:

因为我们没有配置端口,那么默认就是8080,我们访问:http://localhost:8080/consumer/8

一个简单的远程服务调用案例就实现了。

4.有没有问题?

简单回顾一下,刚才我们写了什么:

user-service:对外提供了查询用户的接口

consumer:通过RestTemplate访问http://locahost:8081/user/{id}接口,查询用户数据

存在什么问题?

  • 在consumer中,我们把url地址硬编码到了代码中,不方便后期维护
  • consumer需要记忆user-service的地址,如果出现变更,可能得不到通知,地址将失效
  • consumer不清楚user-service的状态,服务宕机也不知道
  • user-service只有1台服务,不具备高可用性
  • 即便user-service形成集群,consumer还需自己实现负载均衡

其实上面说的问题,概括一下就是分布式服务必然要面临的问题:

  • 服务管理
    • 如何自动注册和发现
    • 如何实现状态监管
    • 如何实现动态路由
  • 服务如何实现负载均衡
  • 服务如何解决容灾问题
  • 服务如何实现统一配置

以上的问题,我们都将在SpringCloud中得到答案。

第六章 Eureka注册中心

是Netflix公司出品,英文直译:发现了,找到了!

1.认识Eureka

首先我们来解决第一问题,服务的管理。

问题分析

在刚才的案例中,user-service对外提供服务,需要对外暴露自己的地址。而consumer(调用者)需要记录服务提供者的地址。将来地址出现变更,还需要及时更新。这在服务较少的时候并不觉得有什么,但是在现在日益复杂的互联网环境,一个项目肯定会拆分出十几,甚至数十个微服务。此时如果还人为管理地址,不仅开发困难,将来测试、发布上线都会非常麻烦,这与DevOps的思想是背道而驰的。

网约车

这就好比是 网约车出现以前,人们出门叫车只能叫出租车。一些私家车想做出租却没有资格,被称为黑车。而很多人想要约车,但是无奈出租车太少,不方便。私家车很多却不敢拦,而且满大街的车,谁知道哪个才是愿意载人的。一个想要,一个愿意给,就是缺少引子,缺乏管理啊。

此时滴滴这样的网约车平台出现了,所有想载客的私家车全部到滴滴注册,记录你的车型(服务类型),身份信息(联系方式)。这样提供服务的私家车,在滴滴那里都能找到,一目了然。

此时要叫车的人,只需要打开APP,输入你的目的地,选择车型(服务类型),滴滴自动安排一个符合需求的车到你面前,为你服务,完美!

Eureka做什么?

Eureka就好比是滴滴,负责管理、记录服务提供者的信息。服务调用者无需自己寻找服务,而是把自己的需求告诉Eureka,然后Eureka会把符合你需求的服务告诉你。

同时,服务提供方与Eureka之间通过“心跳”机制进行监控,当某个服务提供方出现问题,Eureka自然会把它从服务列表中剔除。

这就实现了服务的自动注册、发现、状态监控。

2.原理图

基本架构:

1548578752909

renewal:续约

  • Eureka-Server:就是服务注册中心(可以是一个集群),对外暴露自己的地址。
  • 提供者:启动后向Eureka注册自己信息(地址,服务名称等),并且定期进行服务续约
  • 消费者:服务调用方,会定期去Eureka拉取服务列表,然后使用负载均衡算法选出一个服务进行调用。
  • 心跳(续约):提供者定期通过http方式向Eureka刷新自己的状态

3.入门案例

3.1.编写EurekaServer

接下来我们创建一个项目,启动一个EurekaServer:

image-20201103195345559

依赖:

1<?xml version="1.0" encoding="UTF-8"?> 2<project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <parent> 6 <artifactId>springcloud_demo</artifactId> 7 <groupId>cn.itcast</groupId> 8 <version>1.0-SNAPSHOT</version> 9 </parent> 10 <modelVersion>4.0.0</modelVersion> 11 12 <artifactId>eureka_server</artifactId> 13 14 <dependencies> 15 <dependency> 16 <groupId>org.springframework.cloud</groupId> 17 <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> 18 </dependency> 19 </dependencies> 20</project>

编写启动类:

1@SpringBootApplication 2@EnableEurekaServer // 声明这个应用是一个EurekaServer 3public class EurekaServer { 4 public static void main(String[] args) { 5 SpringApplication.run(EurekaServer.class, args); 6 } 7}

编写配置:

1server: 2 port: 10086 3spring: 4 application: 5 name: eureka-server # 应用名称,会在Eureka中作为服务的id标识(serviceId) 6eureka: 7 client: 8 service-url: # EurekaServer的地址,现在是自己的地址,如果是集群,需要写其它Server的地址。 9 defaultZone: http://127.0.0.1:10086/eureka 10 register-with-eureka: false # 不注册自己 11 fetch-registry: false #不拉取服务

启动服务,并访问:http://127.0.0.1:10086

3.2.服务注册

注册服务,就是在服务上添加Eureka的客户端依赖,客户端代码会自动把服务注册到EurekaServer中。

我们在user-service-demo中添加Eureka客户端依赖:

1<!-- Eureka客户端 --> 2<dependency> 3 <groupId>org.springframework.cloud</groupId> 4 <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> 5</dependency>

在启动类上开启Eureka客户端功能

通过添加@EnableDiscoveryClient来开启Eureka客户端功能

1package cn.itcast; 2 3import org.springframework.boot.SpringApplication; 4import org.springframework.boot.autoconfigure.SpringBootApplication; 5import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6import org.springframework.cloud.netflix.eureka.EnableEurekaClient; 7import tk.mybatis.spring.annotation.MapperScan; 8 9@SpringBootApplication 10@MapperScan("cn.itcast.dao") 11//@EnableEurekaClient 此注解仅支持eureka注册中心 12@EnableDiscoveryClient // 此注解不仅支持eureka注册中心,还支持 像zookeeper等注册中心 13public class UserApplication { 14 15 public static void main(String[] args) { 16 SpringApplication.run(UserApplication.class,args); 17 } 18}

编写配置

1server: 2 port: 8081 3spring: 4 datasource: 5 url: jdbc:mysql://localhost:3306/heima 6 username: root 7 password: 123 8 application: 9 name: user-service ## 应用名称 10eureka: 11 client: 12 service-url: ## EurekaServer地址 13 defaultZone: http://127.0.0.1:10086/eureka

注意:

  • 这里我们添加了spring.application.name属性来指定应用名称,将来会作为服务的id使用。

重启项目,访问Eureka监控页面查看 http://127.0.0.1:10086/eureka

image-20201103200957348

我们发现user-service服务已经注册成功了

3.3.服务发现

接下来我们修改consumer-demo,尝试从EurekaServer获取服务。

方法与消费者类似,只需要在项目中添加EurekaClient依赖,就可以通过服务名称来获取信息了!

1)添加依赖:

1<!-- Eureka客户端 --> 2<dependency> 3 <groupId>org.springframework.cloud</groupId> 4 <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> 5</dependency>

2)在启动类开启Eureka客户端

1@SpringBootApplication 2@EnableDiscoveryClient // 开启Eureka客户端 可以省略 3public class ConsumerApplication { 4 @Bean 5 public RestTemplate restTemplate() { 6 return new RestTemplate(); 7 } 8 public static void main(String[] args) { 9 SpringApplication.run(ConsumerApplication.class, args); 10 } 11}

3)修改配置:

1server: 2 port: 8080 3spring: 4 application: 5 name: consumer ## 应用名称 6eureka: 7 client: 8 service-url: ## EurekaServer地址 9 defaultZone: http://127.0.0.1:10086/eureka

4)修改代码,用DiscoveryClient类的方法,根据服务名称,获取服务实例:

1package cn.itcast.Controller; 2 3import cn.itcast.pojo.User; 4import org.springframework.cloud.client.discovery.DiscoveryClient; 5import org.springframework.beans.factory.annotation.Autowired; 6import org.springframework.cloud.client.ServiceInstance; 7import org.springframework.web.bind.annotation.GetMapping; 8import org.springframework.web.bind.annotation.PathVariable; 9import org.springframework.web.bind.annotation.RequestMapping; 10import org.springframework.web.bind.annotation.RestController; 11import org.springframework.web.client.RestTemplate; 12 13import java.util.List; 14 15/** 16 * @description: 17 * @author: mryhl 18 * @date: Created in 2020/11/3 19:43 19 * @version: 1.0 20 */ 21@RestController 22@RequestMapping("consumer") 23public class ConsumerController { 24 25 @Autowired 26 private RestTemplate restTemplate; 27 28 @Autowired 29 private DiscoveryClient discoveryClient; 30 31 32 @GetMapping("{id}") 33 public User queryById(@PathVariable("id") Integer id){ 34 // 根据服务id(spring.application.name),获取服务实例列表 35 List<ServiceInstance> instances = discoveryClient.getInstances("user-service"); 36 // 取出一个服务实例 37 ServiceInstance instance = instances.get(0); 38 String url = instance.getUri()+"/user/" + id; 39 // 查询 40 User user = restTemplate.getForObject(url, User.class); 41 return user; 42 } 43}

5)Debug跟踪运行:

生成的URL:

这里的ip是本机的局域网ip。

访问结果:

4.Eureka详解

接下来我们详细讲解Eureka的原理及配置。

4.1.基础架构

Eureka架构中的三个核心角色:

  • 服务注册中心

    Eureka的服务端应用,提供服务注册和发现功能,就是刚刚我们建立的eureka-server

  • 服务提供者

    提供服务的应用,可以是SpringBoot应用,也可以是其它任意技术实现,只要对外提供的是Rest风格服务即可。本例中就是我们实现的user-service

  • 服务消费者

    消费应用从注册中心获取服务列表,从而得知每个服务方的信息,知道去哪里调用服务方。本例中就是我们实现的consumer

4.2.高可用的Eureka Server

Eureka Server即服务的注册中心,在刚才的案例中,我们只有一个EurekaServer,事实上EurekaServer也可以是一个集群,形成高可用的Eureka中心。

服务同步

多个Eureka Server之间也会互相注册为服务,当服务提供者注册到Eureka Server集群中的某个节点时,该节点会把服务的信息同步给集群中的每个节点,从而实现高可用集群。因此,无论客户端访问到Eureka Server集群中的任意一个节点,都可以获取到完整的服务列表信息。

而作为客户端,需要把信息注册到每个Eureka中:

1533825644505

如果有三个Eureka,则每一个EurekaServer都需要注册到其它几个Eureka服务中,例如:有三个分别为10086、10087、10088,则:

  • 10086要注册到10087和10088上
  • 10087要注册到10086和10088上
  • 10088要注册到10086和10087上

动手搭建高可用的EurekaServer

我们假设要搭建两条EurekaServer的集群,端口分别为:10086和10087

1)我们修改原来的EurekaServer配置:

1server: 2 port: 10086 ## 端口 3spring: 4 application: 5 name: eureka-server ## 应用名称,会在Eureka中显示 6eureka: 7 client: 8 service-url: ## 配置其他Eureka服务的地址,而不是自己,比如10087 9 defaultZone: http://127.0.0.1:10087/eureka

所谓的高可用注册中心,其实就是把EurekaServer自己也作为一个服务,注册到其它EurekaServer上,这样多个EurekaServer之间就能互相发现对方,从而形成集群。因此我们做了以下修改:

  • 把service-url的值改成了另外一台EurekaServer的地址,而不是自己

此时启动EurekaServer

2)另外一台配置恰好相反:

注意:idea中一个应用不能启动两次,我们需要重新配置一个启动器:

1525615070033

赋值一个启动项

1533825083030

通过JVM参数覆盖配置文件配置:

1556338089508

-Dserver.port=10087 -Deureka.client.serviceUrl.defaultZone=http://127.0.0.1:10086/eureka

image-20201103202412187

然后启动即可。

3)启动测试:

4)客户端注册服务到集群

因为EurekaServer不止一个,因此注册服务的时候,service-url参数需要变化:

1eureka: 2 client: 3 service-url: ## EurekaServer地址,多个地址以','隔开 4 defaultZone: http://127.0.0.1:10086/eureka,http://127.0.0.1:10087/eureka

4.3.Eureka客户端

服务提供者要向EurekaServer注册服务,并且完成服务续约等工作。

服务注册

服务提供者在启动时,会检测配置属性中的:eureka.client.register-with-erueka=true参数是否正确,事实上默认就是true。如果值确实为true,则会向EurekaServer发起一个Rest请求,并携带自己的元数据信息,Eureka Server会把这些信息保存到一个双层Map结构中。

  • 第一层Map的Key就是服务id,一般是配置中的spring.application.name属性
  • 第二层Map的key是服务的实例id。一般host+ serviceId + port,例如:locahost:user-service:8081
  • 值则是服务的实例对象,也就是说一个服务,可以同时启动多个不同实例,形成集群。

user-service默认注册时使用的是主机名,如果我们想用ip进行注册,可以在user-service的application.yml添加配置:

1eureka: 2 instance: 3 ip-address: 127.0.0.1 ## ip地址 4 prefer-ip-address: true ## 更倾向于使用ip,而不是host名 5 instance-id: ${eureka.instance.ip-address}:${server.port} ## 自定义实例的id

服务续约

在注册服务完成以后,服务提供者会维持一个心跳(定时向EurekaServer发起Rest请求),告诉EurekaServer:“我还活着”。这个我们称为服务的续约(renewal);

有两个重要参数可以修改服务续约的行为:

1eureka: 2 instance: 3 lease-renewal-interval-in-seconds: 30 4 lease-expiration-duration-in-seconds: 90
  • lease-renewal-interval-in-seconds:服务续约(renew)的间隔,默认为30秒
  • lease-expiration-duration-in-seconds:服务失效时间,默认值90秒

也就是说,默认情况下每个30秒服务会向注册中心发送一次心跳,证明自己还活着。如果超过90秒没有发送心跳,EurekaServer就会认为该服务宕机,会从服务列表中移除,这两个值在生产环境不要修改,默认即可。

获取服务列表

服务消费者启动时,会检测eureka.client.fetch-registry=true参数的值,如果为true,则会从Eureka Server服务的列表只读备份,然后缓存在本地。并且每隔30秒会重新获取并更新数据。我们可以通过下面的参数来修改:

1eureka: 2 client: 3 registry-fetch-interval-seconds: 30

4.5.服务下线、失效剔除和自我保护

服务下线

当服务进行正常关闭操作时,它会触发一个服务下线的REST请求给Eureka Server,告诉服务注册中心:“我要下线了”。服务中心接受到请求之后,将该服务置为下线状态。

失效剔除

有时我们的服务可能由于内存溢出或网络故障等原因使得服务不能正常的工作,而服务注册中心并未收到“服务下线”的请求。相对于服务提供者的“服务续约”操作,服务注册中心在启动时会创建一个定时任务,默认每隔一段时间(默认为60秒)将当前清单中超时(默认为90秒)没有续约的服务剔除,这个操作被称为失效剔除。

可以通过eureka.server.eviction-interval-timer-in-ms参数对其进行修改,单位是毫秒。

自我保护

我们关停一个服务,就会在Eureka面板看到一条警告:

这是触发了Eureka的自我保护机制。当服务未按时进行心跳续约时,Eureka会统计服务实例最近15分钟心跳续约的比例是否低于了85%。在生产环境下,因为网络延迟等原因,心跳失败实例的比例很有可能超标,但是此时就把服务剔除列表并不妥当,因为服务可能没有宕机。Eureka在这段时间内不会剔除任何服务实例,直到网络恢复正常。生产环境下这很有效,保证了大多数服务依然可用,不过也有可能获取到失败的服务实例,因此服务调用者必须做好服务的失败容错。

我们可以通过下面的配置来关停自我保护:(在eureka注册中心的微服务中配置)

1eureka: 2 server: 3 enable-self-preservation: false ## 关闭自我保护模式(缺省为打开)

总结:

  • 服务的注册和发现都是可控制的,可以关闭也可以开启。默认都是开启
  • 注册后需要心跳,心跳周期默认30秒一次,超过90秒没法认为宕机
  • 服务拉取默认30秒拉取一次
  • Eureka每个60秒会剔除标记为宕机的服务
  • Eureka会有自我保护,当心跳失败比例超过阈值,那么开启自我保护,不再剔除服务。
  • Eureka高可用就是多台Eureka互相注册在对方上

第七章 负载均衡Ribbon

在刚才的案例中,我们启动了一个user-service,然后通过DiscoveryClient来获取服务实例信息,然后获取ip和端口来访问。

但是实际环境中,我们往往会开启很多个user-service的集群。此时我们获取的服务列表中就会有多个,到底该访问哪一个呢?

一般这种情况下我们就需要编写负载均衡算法,在多个实例列表中进行选择。

不过Eureka中已经帮我们集成了负载均衡组件:Ribbon,简单修改代码即可使用。

什么是Ribbon:

1525619257397

接下来,我们就来使用Ribbon实现负载均衡。

1.启动两个服务实例

首先我们启动两个user-service实例,一个8081,一个8082。

和Eureka的高可用配置方式一致,复制启动参数,修改启动端口 -Dserver.port=8082

1533826535457

Eureka监控面板:

2.开启负载均衡

因为Eureka中已经集成了Ribbon,所以我们无需引入新的依赖。直接修改代码:

在RestTemplate的配置方法上添加@LoadBalanced注解:

1package cn.itcast; 2 3import org.springframework.boot.SpringApplication; 4import org.springframework.boot.autoconfigure.SpringBootApplication; 5import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6import org.springframework.cloud.client.loadbalancer.LoadBalanced; 7import org.springframework.context.annotation.Bean; 8import org.springframework.web.client.RestTemplate; 9 10/** 11 * @description: 12 * @author: mryhl 13 * @date: Created in 2020/11/3 19:40 14 * @version: 1.0 15 */ 16@SpringBootApplication 17@EnableDiscoveryClient // 开启Eureka客户端 可以省略 18public class ConsumerApplication { 19 @Bean 20 @LoadBalanced 21 public RestTemplate restTemplate(){ 22 return new RestTemplate(); 23 } 24 25 public static void main(String[] args) { 26 SpringApplication.run(ConsumerApplication.class,args); 27 } 28}

修改调用方式,不再手动获取ip和端口,而是直接通过服务名称调用:

1@GetMapping("{id}") 2public User queryById(@PathVariable("id") Long id){ 3 String url = "http://user-service/user/" + id; 4 User user = restTemplate.getForObject(url, User.class); 5 return user; 6}

访问页面,查看结果:

完美!

3.源码跟踪

为什么我们只输入了service名称就可以访问了呢?之前还要获取ip和端口。

显然有人帮我们根据service名称,获取到了服务实例的ip和端口。它就是LoadBalancerInterceptor,这个类会在对RestTemplate的请求进行拦截,然后从Eureka根据服务id获取服务列表,随后利用负载均衡算法得到真实的服务地址信息,替换服务id。

我们进行源码跟踪:

1525620483637

继续跟入execute方法:发现获取了8082端口的服务

1525620787090

再跟下一次,发现获取的是8081:

1525620835911

果然实现了负载均衡。

源码跟踪

LoadBalancerInterceptor—>RibbonLoadBalancerClient—>DynamicServerListLoadBalancer—>BaseLoadBalancer—>IRule—>RoundRobinRule

​ 获取服务列表(在loadBalancer中查看)

4.负载均衡策略

在刚才的代码中,可以看到获取服务使通过一个getServer方法:

1525620835911

我们继续跟入:

1544361421671

继续跟踪源码chooseServer方法,发现这么一段代码:

1525622652849

我们看看这个rule是谁:

1525622699666

这里的rule默认值是一个RoundRobinRule,看类的介绍:

1525622754316

这不就是轮询的意思嘛。

我们注意到,这个类其实是实现了接口IRule的,查看一下:

1525622817451

定义负载均衡的规则接口。

它有以下实现:

1525622876842

SpringBoot也帮我们提供了修改负载均衡规则的配置入口:(consumer的微服务上配置)

1user-service: 2 ribbon: 3 NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

格式是:{服务名称}.ribbon.NFLoadBalancerRuleClassName,值就是IRule的实现类。

再次测试,发现结果变成了随机:

1525623193949

附加:

Ribbon默认是采用懒加载,即第一次访问时才会去创建负载均衡客户端。往往会出现超时。如果需要采用饥饿加载,即项目启动即创建,可以这样配置:

1ribbon: 2 eager-load: 3 enabled: true 4 clients: user-service

负载均衡的源码流程图:

1551316355275

第八章 Hystrix

1.简介

Hystix,英文意思是豪猪,全身是刺,看起来就不好惹,是一种保护机制。

Hystrix也是Netflix公司的一款组件。

主页:https://github.com/Netflix/Hystrix/

1525658740266

那么Hystix的作用是什么呢?具体要保护什么呢?

Hystix是Netflix开源的一个延迟和容错库,用于隔离访问远程服务、第三方库,防止出现级联失败。

2.雪崩问题

微服务中,服务间调用关系错综复杂,一个请求,可能需要调用多个微服务接口才能实现,会形成非常复杂的调用链路:

1533829099748

如图,一次业务请求,需要调用A、P、H、I四个服务,这四个服务又可能调用其它服务。

如果此时,某个服务出现异常:

1533829198240

例如微服务I发生异常,请求阻塞,用户不会得到响应,则tomcat的这个线程不会释放,于是越来越多的用户请求到来,越来越多的线程会阻塞:

1533829307389

服务器支持的线程和并发数有限,请求一直阻塞,会导致服务器资源耗尽,从而导致所有其它服务都不可用,形成雪崩效应。

这就好比,一个汽车生产线,生产不同的汽车,需要使用不同的零件,如果某个零件因为种种原因无法使用,那么就会造成整台车无法装配,陷入等待零件的状态,直到零件到位,才能继续组装。 此时如果有很多个车型都需要这个零件,那么整个工厂都将陷入等待的状态,导致所有生产都陷入瘫痪。一个零件的波及范围不断扩大。

Hystix解决雪崩问题的手段主要是服务降级,包括:

  • 线程隔离
  • 服务熔断

3.线程隔离,服务降级

3.1.原理

线程隔离示意图:

1533829598310

解读:

Hystrix为每个依赖服务调用分配一个小的线程池,如果线程池已满调用将被立即拒绝,默认不采用排队.加速失败判定时间。

用户的请求将不再直接访问服务,而是通过线程池中的空闲线程来访问服务,如果线程池已满,或者请求超时,则会进行降级处理,什么是服务降级?

服务降级:优先保证核心服务,而非核心服务不可用或弱可用。

用户的请求故障时,不会被阻塞,更不会无休止的等待或者看到系统崩溃,至少可以看到一个执行结果(例如返回友好的提示信息) 。

服务降级虽然会导致请求失败,但是不会导致阻塞,而且最多会影响这个依赖服务对应的线程池中的资源,对其它服务没有响应。

触发Hystix服务降级的情况:

  • 线程池已满
  • 请求超时

3.2.动手实践

引入依赖:

在consumer项目引入依赖

1<!--hystrix熔断器--> 2<dependency> 3 <groupId>org.springframework.cloud</groupId> 4 <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> 5</dependency>

开启熔断:

在启动类上添加注解:@EnableCircuitBreaker

1@SpringBootApplication 2@EnableDiscoveryClient 3@EnableCircuitBreaker 4public class ConsumerApplication { 5 // ... 6}

可以看到,我们类上的注解越来越多,在微服务中,经常会引入上面的三个注解,于是Spring就提供了一个组合注解:@SpringCloudApplication

因此,我们可以使用这个组合注解来代替之前的3个注解。

1@SpringCloudApplication 2public class ConsumerApplication { 3 // ... 4}

编写降级逻辑

当目标服务的调用出现故障,我们希望快速失败,给用户一个友好提示。因此需要提前编写好失败时的降级处理逻辑,要使用HystixCommond来完成:

1package cn.itcast.Controller; 2 3import cn.itcast.pojo.User; 4import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; 5import org.springframework.cloud.client.discovery.DiscoveryClient; 6import org.springframework.beans.factory.annotation.Autowired; 7import org.springframework.cloud.client.ServiceInstance; 8import org.springframework.web.bind.annotation.GetMapping; 9import org.springframework.web.bind.annotation.PathVariable; 10import org.springframework.web.bind.annotation.RequestMapping; 11import org.springframework.web.bind.annotation.RestController; 12import org.springframework.web.client.RestTemplate; 13 14import java.util.List; 15 16/** 17 * @description: 18 * @author: mryhl 19 * @date: Created in 2020/11/3 19:43 20 * @version: 1.0 21 */ 22@RestController 23@RequestMapping("consumer") 24public class ConsumerController { 25 26 @Autowired 27 private RestTemplate restTemplate; 28 29 @Autowired 30 private DiscoveryClient discoveryClient; 31 32 33 @GetMapping("{id}") 34 @HystrixCommand(fallbackMethod = "queryByIdFallBack") 35 public String queryById(@PathVariable("id") Integer id){ 36 // 根据服务id(spring.application.name),获取服务实例列表 37 //List<ServiceInstance> instances = discoveryClient.getInstances("user-service"); 38 // 取出一个服务实例 39 //ServiceInstance instance = instances.get(0); 40 //String url = instance.getUri()+"/user/" + id; 41 String url = "http://user-service/user/" + id; 42 // 查询 43 String user = restTemplate.getForObject(url, String.class); 44 return user; 45 } 46 47 public String queryByIdFallBack(Integer id){ 48 49 return "对不起,网络太拥挤了!"; 50 } 51 52 53}

要注意,因为熔断的降级逻辑方法必须跟正常逻辑方法保证:相同的参数列表和返回值声明。失败逻辑中返回User对象没有太大意义,一般会返回友好提示。所以我们把queryById的方法改造为返回String,反正也是Json数据。这样失败逻辑中返回一个错误说明,会比较方便。

说明:

  • @HystrixCommand(fallbackMethod = “queryByIdFallBack”):用来声明一个降级逻辑的方法

测试:

当user-service正常提供服务时,访问与以前一致。但是当我们将user-service停机时,会发现页面返回了降级处理信息:

默认的Fallback

我们刚才把fallback写在了某个业务方法上,如果这样的方法很多,那岂不是要写很多。所以我们可以把Fallback配置加在类上,实现默认fallback:

1package cn.itcast.Controller; 2 3import cn.itcast.pojo.User; 4import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties; 5import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; 6import org.springframework.cloud.client.discovery.DiscoveryClient; 7import org.springframework.beans.factory.annotation.Autowired; 8import org.springframework.cloud.client.ServiceInstance; 9import org.springframework.web.bind.annotation.GetMapping; 10import org.springframework.web.bind.annotation.PathVariable; 11import org.springframework.web.bind.annotation.RequestMapping; 12import org.springframework.web.bind.annotation.RestController; 13import org.springframework.web.client.RestTemplate; 14 15import java.util.List; 16 17/** 18 * @description: 19 * @author: mryhl 20 * @date: Created in 2020/11/3 19:43 21 * @version: 1.0 22 */ 23@RestController 24@RequestMapping("consumer") 25@DefaultProperties(defaultFallback = "defaultFallBack") 26public class ConsumerController { 27 28 @Autowired 29 private RestTemplate restTemplate; 30 31 @Autowired 32 private DiscoveryClient discoveryClient; 33 34 35 @GetMapping("{id}") 36 //@HystrixCommand(fallbackMethod = "queryByIdFallBack") 37 38 public String queryById(@PathVariable("id") Integer id){ 39 // 根据服务id(spring.application.name),获取服务实例列表 40 //List<ServiceInstance> instances = discoveryClient.getInstances("user-service"); 41 // 取出一个服务实例 42 //ServiceInstance instance = instances.get(0); 43 //String url = instance.getUri()+"/user/" + id; 44 if(id==1){ 45 throw new RuntimeException("服务器忙。。。"); 46 } 47 48 String url = "http://user-service/user/" + id; 49 // 查询 50 String user = restTemplate.getForObject(url, String.class); 51 return user; 52 } 53 54 public String queryByIdFallBack(Integer id){ 55 56 return "对不起,网络太拥挤了!"; 57 } 58 59 public String defaultFallBack(){ 60 return "默认提示:对不起,网络太拥挤了!"; 61 } 62 63}
  • @DefaultProperties(defaultFallback = “defaultFallBack”):在类上指明统一的失败降级方法

1533858138646

超时设置:

在之前的案例中,请求在超过1秒后都会返回错误信息,这是因为Hystix的默认超时时长为1,我们可以通过配置修改这个值:(以下书写没有提示,可以直接拷贝测试)

1hystrix: 2 command: 3 default: 4 execution: 5 isolation: 6 thread: 7 timeoutInMilliseconds: 2000

这个配置会作用于全局所有方法。

为了触发超时,我们可以在user-service中休眠2秒:

1@Service 2public class UserService { 3 4 @Autowired 5 private UserMapper userMapper; 6 7 public User queryById(Long id) { 8 try { 9 Thread.sleep(2000); 10 } catch (InterruptedException e) { 11 e.printStackTrace(); 12 } 13 return userMapper.selectByPrimaryKey(id); 14 } 15}

测试:

可以发现,请求的时长已经到了2.01s,证明配置生效了。

如果把修改时间修改到2秒以下,又可以正常访问了。

4.服务熔断:

4.1.熔断原理

熔断器,也叫断路器,其英文单词为:Circuit Breaker

1525658640314

Hystix的熔断状态机模型:

1533830345149

状态机有3个状态:

  • Closed:关闭状态(断路器关闭),所有请求都正常访问。
  • Open:打开状态(断路器打开),所有请求都会被降级。Hystix会对请求情况计数,当一定时间内失败请求百分比达到阈值,则触发熔断,断路器会完全关闭。默认失败比例的阈值是50%,请求次数最少不低于20次。
  • Half Open:半开状态,open状态不是永久的,打开后会进入休眠时间(默认是5S)。随后断路器会自动进入半开状态。此时会释放1次请求通过,若这个请求是健康的,则会关闭断路器,否则继续保持打开,再次进行5秒休眠计时。

4.2.动手实践

为了能够精确控制请求的成功或失败,我们在consumer的调用业务中加入一段逻辑:

1@GetMapping("{id}") 2 //@HystrixCommand(fallbackMethod = "queryByIdFallBack") 3 @HystrixCommand 4 public String queryById(@PathVariable("id") Integer id){ 5 // 根据服务id(spring.application.name),获取服务实例列表 6 //List<ServiceInstance> instances = discoveryClient.getInstances("user-service"); 7 // 取出一个服务实例 8 //ServiceInstance instance = instances.get(0); 9 //String url = instance.getUri()+"/user/" + id; 10 if(id==1){ 11 throw new RuntimeException("服务器忙。。。"); 12 } 13 14 String url = "http://user-service/user/" + id; 15 // 查询 16 String user = restTemplate.getForObject(url, String.class); 17 return user; 18 }

这样如果参数是id为1,一定失败,其它情况都成功。(不要忘了清空user-service中的休眠逻辑)

我们准备两个请求窗口:

熔断器的默认触发阈值是20次请求,不好触发。休眠时间时5秒,时间太短,不易观察,为了测试方便,我们可以通过配置修改熔断策略:

1hystrix: 2 command: 3 default: 4 circuitBreaker: 5 requestVolumeThreshold: 10 6 sleepWindowInMilliseconds: 10000 7 errorThresholdPercentage: 50

解读:

  • requestVolumeThreshold:触发熔断的最小请求次数,默认10
  • sleepWindowInMilliseconds:休眠时长,默认是10000毫秒
  • errorThresholdPercentage:触发熔断的失败请求最小占比,默认50%

当我们疯狂访问id为1的请求时(超过5次),就会触发熔断。断路器会端口,一切请求都会被降级处理。

此时你访问id为2的请求,会发现返回的也是失败,而且失败时间很短,只有20毫秒左右:

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )