Spring Cloud Netflix

SpringCloud入门

官网
SpringCloud, 基于SpringBoot提供了一套微服务解决方案,包括服务注册与发现,配置中心,全链路监
控,服务网关,负载均衡,熔断器等组件,除了基于NetFlix的开源组件做高度抽象封装之外,还有一些
选型中立的开源组件。
SpringCloud利用SpringBoot的开发便利性,巧妙地简化了分布式系统基础设施的开发,SpringCloud为
开发人员提供了快速构建分布式系统的一些工具,包括配置管理,服务发现,断路器,路由,微代理,
事件总线,全局锁,决策竞选,分布式会话等等,他们都可以用SpringBoot的开发风格做到一键启动和
部署。
SpringBoot并没有重复造轮子,它只是将目前各家公司开发的比较成熟,经得起实际考研的服务框架组
合起来,通过SpringBoot风格进行再封装,屏蔽掉了复杂的配置和实现原理,最终给开发者留出了一套
简单易懂,易部署和易维护的分布式系统开发工具包
SpringCloud 是 分布式微服务架构下的一站式解决方案,是各个微服务架构落地技术的集合体,俗称微
服务全家桶。

SpringCloud和SpringBoot关系

SpringBoot专注于快速方便的开发单个个体微服务。
SpringCloud是关注全局的微服务协调整理治理框架,它将SpringBoot开发的一个个单体微服务整合并
管理起来,为各个微服务之间提供:配置管理,服务发现,断路器,路由,微代理,事件总线,全局锁,决策竞选,分布式会话等等集成服务。
SpringBoot可以离开SpringClooud独立使用,开发项目,但是SpringCloud离不开SpringBoot,属于依
赖关系
SpringBoot专注于快速、方便的开发单个个体微服务,SpringCloud关注全局的服务治理框架

在这里插入图片描述
Spring Cloud是一个由众多独立子项目组成的大型综合项目,每个子项目有不同的发行节奏,都维护着
自己的发布版本号。Spring Cloud通过一个资源清单BOM(Bill of Materials)来管理每个版本的子项目
清单。为避免与子项目的发布号混淆,所以没有采用版本号的方式,而是通过命名的方式。
这些版本名称的命名方式采用了伦敦地铁站的名称,同时根据字母表的顺序来对应版本时间顺序,比
如:最早的Release版本:Angel,第二个Release版本:Brixton,然后是Camden、Dalston、
Edgware,Finchley,目前最新的是 Hoxton 版本。

参考
https://springcloud.cc/spring-cloud-netflix.html
中文API文档:https://springcloud.cc/spring-cloud-dalston.html
SpringCloud中国社区 http://springcloud.cn/
SpringCloud中文网 https://springcloud.cc

SpringCloud版本选择

在这里插入图片描述
springcloud.pom

<properties>
        <spring.cloud-version>Hoxton.SR8</spring.cloud-version>
        <spring.boot-version>2.3.3.RELEASE</spring.boot-version>
    </properties>
    <dependencyManagement>
        <dependencies>
      <!--spring-cloud依赖-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring.cloud-version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!---=springboot依赖-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring.boot-version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--springboot启动器-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
                <version>${spring.boot-version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        
        </dependencies>
            </dependencyManagement>

Eureka服务注册与发现

Netflix 在设计Eureka 时,遵循的就是AP原则
CAP原则又称CAP定理,指的是在一个分布式系统中

  • 一致性(Consistency)
  • 可用性(Availability)
  • 分区容错性(Partition tolerance)
    CAP 原则指的是,这三个要素最多只能同时实现两点,不可能三者兼顾。
    在这里插入图片描述

Eureka的基本架构:
SpringCloud 封装了NetFlix公司开发的Eureka模块来实现服务注册和发现
Eureka采用了C-S的架构设计,EurekaServer 作为服务注册功能的服务器,他是服务注册中心
而系统中的其他微服务。使用Eureka的客户端连接到EurekaServer并维持心跳连接。这样系统的维护人
员就可以通过EurekaServer来监控系统中各个微服务是否正常运行,SpringCloud的一些其他模块(比
如Zuul)就可以通过EurekaServer来发现系统中的其他微服务,并执行相关的逻辑;

Eureka 包含两个组件:Eureka ServerEureka Client

Eureka Server 提供服务注册服务,各个节点启动后,会在EurekaServer中进行注册,这样EurekaServer中的服务注册表中将会存储所有可用服务节点的信息,服务节点的信息可以在界面中直观的看到。
Eureka Client是一个Java客户端,用于简化EurekaServer的交互,客户端同时也具备一个内置的使用轮询负载算法的负载均衡器。在应用启动后,将会向EurekaServer发送心跳(默认周期为30秒)。如果Eureka Server在多个心跳周期内没有接收到某个节点的心跳,EurekaServer将会从服务注册表中把这
个服务节点移除掉(默认周期为90秒)

三大角色

  • Eureka Server:提供服务的注册于发现。
  • Service Provider:将自身服务注册到Eureka中,从而使消费方能够找到。
  • Service Consumer:服务消费方从Eureka中获取注册服务列表,从而找到消费服务。

springcloudeureka配置
springcloudeureka配置

对比Zookeeper

回顾CAP原则
RDBMS (Mysql、Oracle、sqlServer)=>ACID
NoSQL(redis、mongdb)
=> CAP

ACID是什么?

  • A(Atomicity)原子性
  • C(Consistency) 一致性
  • I (Isolation)隔离性
  • D(Durability)持久性

CAP是什么?

  • C(Consistency)强一致性
  • A(Availability)可用性
  • P(Partition tolerance)分区容错性
    CAP的三进二:CA、AP、CP

CAP理论的核心

一个分布式系统不可能同时很好的满足一致性,可用性和分区容错性这三个需求
根据CAP原理,将NoSQL数据库分成了满足CA原则,满足CP原则和满足AP原则三大类:

  • CA:单点集群,满足一致性,可用性的系统,通常可扩展性较差
  • CP:满足一致性,分区容错性的系统,通常性能不是特别高
  • AP:满足可用性,分区容错性的系统,通常可能对一致性要求低一些

作为服务注册中心,Eureka比Zookeeper好在哪里?

Zookeeper保证的是CP
当向注册中心查询服务列表时,我们可以容忍注册中心返回的是几分钟以前的注册信息,但不能接受服
务直接down掉不可用。也就是说,服务注册功能对可用性的要求要高于一致性。但是zk会出现这样一种
情况,当master节点因为网络故障与其他节点失去联系时,剩余节点会重新进行leader选举。问题在
于,选举leader的时间太长,30~120s,且选举期间整个zk集群都是不可用的,这就导致在选举期间注
册服务瘫痪。在云部署的环境下,因为网络问题使得zk集群失去master节点是较大概率会发生的事件,
虽然服务最终能够恢复,但是漫长的选举时间导致的注册长期不可用是不能容忍的。
Eureka保证的是AP
Eureka看明白了这一点,因此在设计时就优先保证可用性。Eureka各个节点都是平等的,几个节点挂掉不会影响正常节点的工作,剩余的节点依然可以提供注册和查询服务。而Eureka的客户端在向某个Eureka注册时,如果发现连接失败,则会自动切换至其他节点,只要有一台Eureka还在,就能保住注册服务的可用性,只不过查到的信息可能不是最新的,除此之外,Eureka还有一种自我保护机制,如果在15分钟内超过85%的节点都没有正常的心跳,那么Eureka就认为客户端与注册中心出现了网络故障,此出现以下几种情况:

  1. Eureka不再从注册列表中移除因为长时间没收到心跳而应该过期的服务
  2. Eureka仍然能够接受新服务的注册和查询请求,但是不会被同步到其他节点上(即保证当前节点依
    然可用)
  3. 当网络稳定时,当前实例新的注册信息会被同步到其他节点中
    因此,Eureka可以很好的应对因网络故障导致部分节点失去联系的情况,而不会像zookeeper那样使整
    个注册服务瘫痪

服务构建

eureka服务端
pom

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <!-- eureka-server服务端 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>
    </dependencies>

application.yml

server:
  port: 7001

#eureka配置

eureka:
  instance:
    hostname: localhost #服务注册中心实例的主机名
  client:
    register-with-eureka: false #实例是否在eureka服务器上注册自己的信息以供其他服务发现,默认为true
    fetch-registry: false #此客户端是否获取eureka服务器注册表上的注册信息,默认为true
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/ #与Eureka注册服务中心的通信zone和url地址

编写主启动类

@SpringBootApplication
@EnableEurekaServer //Eureka启动类,接受别人注册进来
public class springbootApplication7001 {
    public static void main(String[] args) {
        SpringApplication.run(springbootApplication7001.class,args);
    }
}

启动,访问测试:
在这里插入图片描述
System Status:系统信息
DS Replicas:服务器副本
Instances currently registered with Eureka:已注册的微服务列表
General Info:一般信息
Instance Info:实例信息

Service Provider

pom

        <!--eureka配置-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>
          <!--完善监控信息-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

yml

server:
  port: 8001
mybatis-plus:
  mapper-locations: classpath:mapper/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  # 控制台输出日志



#spring配置
spring:
  application:
    name: provider-crud
  datasource:
    data-username: root
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springcloud1?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
    username: root
    password: 123456


#eureka配置,讲服务注册到注册中心(集群配置)
eureka:
  instance:
    hostname: localhost #服务注册中心实例的主机名
    instance-id: springcloud-provider-crud-8001
    prefer-ip-address: true
  client:
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:7001/eureka/,http://eureka7002.com/eureka/,http://eureka7003.com/eureka/ #与Eureka注册服务中心的通信zone和url地址
#info配置(完善监控信息)actuator
info:
  app.name: "服务提供者者8001"
  commpny.name: com.zhoukun

启动类

@SpringBootApplication
@EnableEurekaClient //在服务启动后注册到eureka中
public class springbootApplication8001 {

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

服务端也有了,客户端也有了,启动7001,再启动8001,测试访问
在这里插入图片描述

Ribbon负载均衡

Ribbon是什么?

Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具
简单的说,Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法,将NetFlix的间层服务连接在一起。Ribbon的客户端组件提供一系列完整的配置项如:连接超时、重试等等。简单的说,就是在配置文件中列出LoadBalancer(简称LB:负载均衡)后面所有的机器,Ribbon会自动的帮助你基于某种规则(如简单轮询,随机连接等等)去连接这些机器。我们也很容易使用Ribbon实现自定义的负载均衡算法!

Ribbon能干嘛?

LB,即负载均衡(Load Balance),在微服务或分布式集群中经常用的一种应用。负载均衡简单的说就是将用户的请求平摊的分配到多个服务上,从而达到系统的HA(高可用)。常见的负载均衡软件有 Nginx,Lvs 等等Dubbo、SpringCloud中均给我们提供了负载均衡,SpringCloud的负载均衡算法可以自定义负载均衡简单分类

  • 集中式LB
    即在服务的消费方和提供方之间使用独立的LB设施如之前学习的Nginx,由该设施负责把访问请求通过某种策略转发至服务的提供方!
  • 进程式LB
    将LB逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后自己再从这些地址中选出一个合适的服务器。Ribbon就属于进程内LB,它只是一个类库,集成于消费方进程,消费方通过它来获取到服务提供方的地址!

Ribbon的github地址 : https://github.com/NetFlix/ribbon
示例:
pom

        <!--ribbon负载均衡-->
        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-ribbon -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>

yml

server:
  port: 80


#eureka配置
eureka:
  client:
    register-with-eureka: false #不向注册中心注册自己
    serviceUrl:
      defaultZone: http://localhost:7001/eureka/,http://eureka7002.com/eureka/,http://eureka7003.com/eureka/ #与Eureka注册服务中心的通信zone和url地址

对里面的ConfigBean方法加上注解@LoadBalanced在 获得Rest时加入Ribbon的配置;

@Bean
@LoadBalanced //Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工public RestTemplate getRestTemplate(){
return new RestTemplate();
}

修改DeptConsumerController客户端访问类,之前的写的地址是写死的,现在需要变化!

@RestController
public class ConsController {

    @Autowired
    RestTemplate restTemplate;
    //private static final String REST_URL_PREFIX="http://localhost:8081";
    //通过服务名访问
    private static final String REST_URL_PREFIX="http://PROVIDER-CRUD";
    @GetMapping("/cons/getid/{id}")
    public scinfo getid(@PathVariable Long id)
    {
        return restTemplate.getForObject(REST_URL_PREFIX+"/queryId/+"+id,scinfo.class);
    }

    @PostMapping("/cons/add/{name}")
    public boolean add(@PathVariable String name)
    {
        return restTemplate.postForObject(REST_URL_PREFIX+"/add/"+name,name,boolean.class);
    }

    @GetMapping("/cons/get")
    public List get()
    {
        return restTemplate.getForObject(REST_URL_PREFIX+"/query/",List.class);
    }

}

主启动类添加@EnableEurekaClient

@SpringBootApplication
@EnableEurekaClient //在服务启动后注册到eureka中
@RibbonClient(name = "PROVIDER-CRUD",configuration = myrule.class)
public class springbootApplication80 {
    public static void main(String[] args) {
        SpringApplication.run(springbootApplication80.class,args);
    }
}

启动,测试

Feign负载均衡

feign是声明式的web service客户端,它让微服务之间的调用变得更简单了,类似controller调用
service。
Spring Cloud集成了Ribbon和Eureka,可在使用Feign时提供负载均衡的http客户端。
只需要创建一个接口,然后添加注解即可!
feign ,主要是社区,大家都习惯面向接口编程。这个是很多开发人员的规范。调用微服务访问两种方法

  1. 微服务名字 【ribbon】
  2. 接口和注解 【feign 】

Feign能干什么?

  • Feign旨在使编写Java Http客户端变得更容易
  • 前面在使用Ribbon + RestTemplate时,利用RestTemplate对Http请求的封装处理,形成了一套模
    板化的调用方法。但是在实际开发中,由于对服务依赖的调用可能不止一处,往往一个接口会被多
    处调用,所以通常都会针对每个微服务自行封装一些客户端类来包装这些依赖服务的调用。所以,
    Feign在此基础上做了进一步封装,由他 来帮助我们定义和实现依赖服务接口的定义,**在Feign的实
    现下,我们只需要创建一个接口并使用注解的方式来配置它(类似于以前Dao接口上标注Mapper
    注解,现在是一个微服务接口上面标注一个Feign注解即可。)**即可完成对服务提供方的接口绑
    定,简化了使用Spring Cloud Ribbon时,自动封装服务调用客户端的开发量。

Feign集成了Ribbon

利用Ribbon维护了springcloud-Dept的服务列表信息,并且通过轮询实现了客户端的负载均衡,
而与Ribbon不同的是,通过Feign只需要定义服务绑定接口且以声明式的方法,优雅而且简单的实
现了服务调用。
feign
示例

示例

        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>
@Controller
@FeignClient(value = "provider-crud")
public interface FergnServiceClient {
    //添加
    @PostMapping("/add/{name}")
    boolean add(@PathVariable("name") String name);

    //查询单个
    @GetMapping("/queryId/{id}")
    scinfo queryId(@PathVariable("id") Long id);


    @GetMapping("/query")
    List query();

}

上面是最简单的feign client的使用,声明完为feign client后,其他spring管理的类,如service就可以直接注入使用了,例如:

@RestController
public class ConsController {

    @Autowired
    FergnServiceClient service;

    @GetMapping("/cons/getid/{id}")
    public scinfo getid(@PathVariable Long id)
    {
        return this.service.queryId(id);
    }

    @PostMapping("/cons/add/{name}")
    public boolean add(@PathVariable String name)
    {
        return this.service.add(name);
    }

    @GetMapping("/cons/get")
    public List get()
    {
        System.out.println("========>");
        return this.service.query();
    }

    @GetMapping("/get")
    public String geti ()
    {

        return "==================>";
    }

}

springboot启动类

@SpringBootApplication
@EnableEurekaClient //在服务启动后注册到eureka中
@EnableFeignClients
@EnableDiscoveryClient
public class springbootApplication80 {
    public static void main(String[] args) {
        SpringApplication.run(springbootApplication80.class,args);
    }
}

server:
  port: 80


#eureka配置
eureka:
  client:
    register-with-eureka: false #不向注册中心注册自己
    serviceUrl:
      defaultZone: http://localhost:7001/eureka/,http://eureka7002.com/eureka/,http://eureka7003.com/eureka/ #与Eureka注册服务中心的通信zone和url地址
ribbon:
  eureka:
    enabled: true

      #NFLoadBalancerRuleClassName: com.netflix.loadbalancer.BestAvailableRule #配置规则 最空闲连接策略
      #    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #配置规则 随机
      #    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule #配置规则 轮询
      #    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RetryRule #配置规则 重试
      #    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule #配置规则 响应时间权重
      NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #配置规则 最空闲连接策略
      

Hystrix断路器

分布式系统面临的问题
复杂分布式体系结构中的应用程序有数十个依赖关系,每个依赖关系在某些时候将不可避免的失败!
在这里插入图片描述
服务雪崩
多个微服务之间调用的时候,假设微服务A调用微服务B和微服务C,微服务B 和微服务C又调用其他的微
服务,这就是所谓的 “扇出”、如果扇出的链路上某个微服务的调用响应时间过长或者不可用,对微服务A
的调用就会占用越来越多的系统资源,进而引起系统崩溃,所谓的 “雪崩效应”。
对于高流量的应用来说,单一的后端依赖可能会导致所有服务器上的所有资源都在几秒中内饱和。比失
败更糟糕的是,这些应用程序还可能导致服务之间的延迟增加,备份队列,线程和其他系统资源紧张,
导致整个系统发生更多的级联故障,这些都表示需要对故障和延迟进行隔离和管理,以便单个依赖关系
的失败,不能取消整个应用程序或系统。
我们需要 ·弃车保帅

什么是Hystrix

官网

Hystrix是一个用于处理分布式系统的延迟和容错的开源库,在分布式系统里,许多依赖不可避免的会调用失败,比如超时,异常等,Hystrix能够保证在一个依赖出问题的情况下,不会导致整体服务失败,避免级联故障,以提高分布式系统的弹性。“断路器” 本身是一种开关装置,当某个服务单元发生故障之后,通过断路器的故障监控(类似熔断保险丝),向调用方返回一个服务预期的,可处理的备选响应(FallBack),而不是长时间的等待或者抛出调用方法无法处理的异常,这样就可以保证了服务调用方的线程不会被长时间,不必要的占用,从而避免了故障在分布式系统中的蔓延,乃至雪崩.

能干嘛

  • 服务降级
  • 服务熔断
  • 服务限流
  • 接近实时的监控

Hystrix配置参数讲解:

// 是否开启断路器
 @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
 // 至少有3个请求才进行熔断错误比率计算(请求次数)
 /**
  * 设置在一个滚动窗口中,打开断路器的最少请求数。
  比如:如果值是20,在一个窗口内(比如10秒),收到19个请求,即使这19个请求都失败了,断路器也不会打开。
  */
 @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
 //当出错率超过50%后熔断器启动
 @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
 // 熔断器工作时间,超过这个时间,先放一个请求进去,成功的话就关闭熔断,失败就再等一段时间
 @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000")
@HystrixProperty(name = "coreSize", value = "30"),
 /**
  * BlockingQueue的最大队列数,当设为-1,会使用SynchronousQueue,值为正时使用LinkedBlcokingQueue。
  */
 @HystrixProperty(name = "maxQueueSize", value = "101"),
 /**
  * 设置存活时间,单位分钟。如果coreSize小于maximumSize,那么该属性控制一个线程从实用完成到被释放的时间.
  */

/**
  我们知道,线程池内核心线程数目都在忙碌,再有新的请求到达时,线程池容量可以被扩充为到最大数量。
等到线程池空闲后,多于核心数量的线程还会被回收,此值指定了线程被回收前的存活时间,默认为 2,即两分钟。
*/
 @HystrixProperty(name = "keepAliveTimeMinutes", value = "2"),
 /**
  * 设置队列拒绝的阈值,即使maxQueueSize还没有达到
  */
 @HystrixProperty(name = "queueSizeRejectionThreshold", value = "15"),

// 滑动统计的桶数量
 /**
  * 设置一个rolling window被划分的数量,若numBuckets=10,rolling window=10000,
  *那么一个bucket的时间即1秒。必须符合rolling window % numberBuckets == 0。默认1
  */
 @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10"),
 // 设置滑动窗口的统计时间。熔断器使用这个时间
 /** 设置统计的时间窗口值的,毫秒值。
  circuit break 的打开会根据1个rolling window的统计来计算。
  若rolling window被设为10000毫秒,则rolling window会被分成n个buckets,
  每个bucket包含success,failure,timeout,rejection的次数的统计信息。默认10000
  **/
 @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")


fallbackMethod:方法执行时熔断、错误、超时时会执行的回退方法,需要保持此方法与 Hystrix 方法的签名和返回值一致。

defaultFallback:默认回退方法,当配置 fallbackMethod 项时此项没有意义,另外,默认回退方法不能有参数,返回值要与 Hystrix方法的返回值相同。

服务熔断

熔断机制是对应雪崩效应的一种微服务链路保护机制。
当扇出链路的某个微服务不可用或者响应时间太长时,会进行服务的降级,进而熔断该节点微服务调用,快速返回 错误的响应信息。当检测到该节点微服务调用响应正常后恢复调用链路。在SpringCloud框架里熔断机制通过Hystrix实现。Hystrix会监控微服务间调用的状况,当失败的调用到一定阈值,缺省是5秒内20次调用失败就会启动熔断机制。熔断机制的注解是 @HystrixCommand

pom

     <!--Hystrix-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>
    //查询单个
    //一旦调用服务方法失败并抛出了错误信息后
	// 会自动调用HystrixCommand标注好的fallbackMethod调用类中指定方法
    @GetMapping("/queryId/{id}")
    @HystrixCommand(fallbackMethod = "queryIderror")
    public scinfo queryId(@PathVariable Long id)
    {
       scinfo info= service.getById(id);
     //  int i=1/0;
       if(info==null)
       {
            throw new RuntimeException("===>该用户信息未找到"+id);
       }
        return info;
    }

    一旦调用服务方法失败并抛出了错误信息后
     会自动调用HystrixCommand标注好的fallbackMethod调用类中指定方法
    public scinfo queryIderror(@PathVariable Long id)
    {
        return new scinfo().setDbname("没有该用户信息");
    }

启动类@EnableCircuitBreaker

@MapperScan("com.sec.Mapper")
@SpringBootApplication
@EnableEurekaClient //在服务启动后注册到eureka中
@EnableCircuitBreaker   //添加对熔断的支持
public class HystrixspringbootApplication8001 {

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

服务降级

是什么
整体资源快不够了,忍痛将某些服务先关掉,待渡过难关,再开启回来。
服务降级处理是在客户端实现完成的,与服务端没有关系修改springcloud-api工程,根据已经有的接口新建一个实现了FallbackFactory接口的类

@Component
public class HystrxbackFactory implements FallbackFactory<FergnServiceClient> {
    public FergnServiceClient create(Throwable throwable) {
        return new FergnServiceClient() {
            public boolean add(String name) {
                return false;
            }

            public scinfo queryId(Long id) {
                return new scinfo().setName("没有对应的信息,Consumer客户端提供的降级信息,此刻服务Provider已经关闭");
            }

            public List query() {
                return null;
            }
        };
    }
}

修改springcloud-api工程,FergnServiceClient接口在注解 @FeignClient中添加fallbackFactory属性值

@Controller
@FeignClient(value = "provider-crud",fallbackFactory =HystrxbackFactory.class)
public interface FergnServiceClient {
    //添加
    @PostMapping("/add/{name}")
    boolean add(@PathVariable("name") String name);

    //查询单个
    @GetMapping("/queryId/{id}")
    scinfo queryId(@PathVariable("id") Long id);


    @GetMapping("/query")
    List query();

}


springcloud-consumer-dept-feign-80工程修改YML
开启

feign:
  hystrix:
    enabled: true
server:
  port: 80



#eureka配置
eureka:
  client:
    register-with-eureka: false #不向注册中心注册自己
    serviceUrl:
      defaultZone: http://localhost:7001/eureka/,http://eureka7002.com/eureka/,http://eureka7003.com/eureka/ #与Eureka注册服务中心的通信zone和url地址
ribbon:
  eureka:
    enabled: true
      #NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #配置规则 最空闲连接策略
      #NFLoadBalancerRuleClassName: com.netflix.loadbalancer.BestAvailableRule #配置规则 最空闲连接策略
      #    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #配置规则 随机
      #    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule #配置规则 轮询
      #    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RetryRule #配置规则 重试
      #    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule #配置规则 响应时间权重

feign:
  hystrix:
    enabled: true



测试,关闭服务
在这里插入图片描述
服务熔断:一般是某个服务故障或者异常引起,类似现实世界中的 “保险丝” , 当某个异常条件被触发,直接熔断整个服务,而不是一直等到此服务超时!
服务降级:所谓降级,一般是从整体负荷考虑,就是当某个服务熔断之后,服务器将不再被调用,此时客户端可以自己准备一个本地的fallback回调,返回一个缺省值。这样做,虽然服务水平下降,但好歹可用,比直接挂掉要强。

服务监控hystrixDashboard

除了隔离依赖服务的调用以外,Hystrix还提供了准实时的调用监控(Hystrix Dashboard),Hystrix会持续地记录所有通过Hystrix发起的请求的执行信息,并以统计报表和图形的形式展示给用户,包括每秒执行多少请求,多少成功,多少失败等等。Netflix通过hystrix-metrics-event-stream项目实现了对以上指标的监控,SpringCloud也提供了HystrixDashboard的整合,对监控内容转化成可视化界面!
在这里插入图片描述
新建工程springcloud-consumer-hystrix-dashboard-9001
pom

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-hystrix</artifactId>
        <version>1.4.7.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
        <version>1.4.7.RELEASE</version>
    </dependency>


</dependencies>

启动类添加配置@EnableHystrixDashboard

@SpringBootApplication
@EnableHystrixDashboard
public class hystrxDashboardApplication {
    public static void main(String[] args) {
        SpringApplication.run(hystrxDashboardApplication.class,args);
    }

}

yml

server:
  port: 9001

hystrix:
  dashboard:
    proxy-stream-allow-list: "*"

启动springcloud-consumer-hystrix-dashboard-9001该微服务监控消费端
http://localhost:9001/hystrix在这里插入图片描述

所有的Provider微服务提供类 都需要监控依赖配置

<!--actuator监控信息完善-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

    <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>

测试

  1. 启动eureka集群
  2. 启动springcloud-consumer-hystrix-dashboard-9001
  3. 在 springcloud-provider-dept-hystrix-8001 启动类中增加一个bean
@Bean
public ServletRegistrationBean hystrixMetricsStreamServlet() {
ServletRegistrationBean registration = new
ServletRegistrationBean(new HystrixMetricsStreamServlet());
registration.addUrlMappings("/actuator/hystrix.stream");
return registration;
}

被监控服务启动类

@MapperScan("com.sec.Mapper")
@SpringBootApplication
@EnableEurekaClient //在服务启动后注册到eureka中
@EnableCircuitBreaker   //添加对熔断的支持
public class HystrixspringbootApplication8001 {

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

    //需加入该关键代码
    @Bean
    public ServletRegistrationBean hystrixMetricsStreamServlet(){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new HystrixMetricsStreamServlet());
        registrationBean.addUrlMappings("/actuator/hystrix.stream");
        return registrationBean;
    }
}

请求一定要是hystrix配置熔断的方法才有效,不然监控不到
在这里插入图片描述
启动 springcloud-provider-dept-hystrix-8001

  1. http://localhost:8001/dept/get/1
  2. http://localhost:8001/actuator/hystrix.stream 【查看1秒一动的数据流】

监控测试

添加监控地址
在这里插入图片描述

Delay : 该参数用来控制服务器上轮询监控信息的延迟时间,默认为2000毫秒,可以通过配置
该属性来降低客户端的网络和CPU消耗
Title : 该参数对应了头部标题HystrixStream之后的内容,默认会使用具体监控实例URL,可以通过配置该信息来展示更合适的标题。

监控结果
在这里插入图片描述
解决:SpringCloud出现Unable to connect to Command Metric Stream.的异常
解决:SpringCloud出现Unable to connect to Command Metric Stream.的异常

Zuul路由网关

什么是Zuul?
Zuul包含了对请求的路由过滤两个最主要的功能:
其中路由功能负责将外部请求转发到具体的微服务实例上,是实现外部访问统一入口的基础,而过滤器功能则负责对请求的处理过程进行干预,是实现请求校验,服务聚合等功能的基础。Zuul和Eureka进行整合,将Zuul自身注册为Eureka服务治理下的应用,同时从Eureka中获得其他微服务的消息,也即以后的访问微服务都是通过Zuul跳转后获得。
注意:Zuul服务最终还是会注册进Eureka
提供:代理 + 路由 + 过滤 三大功能!

Zuul能干嘛?

路由的基本配置

路由基本配置

pom文件

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-zuul</artifactId>
        <version>1.4.7.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
        <version>1.4.7.RELEASE</version>
    </dependency>

</dependencies>

application.yaml配置

server:
  port: 9527

spring:
  application:
    name: springcloud-zuul


eureka:
  instance:
    hostname: localhost #服务注册中心实例的主机名
    instance-id: springcloud-zuul-9527 #true访问路径可以显示IP地址
    prefer-ip-address: false #true访问路径可以显示IP地址
  client:
    service-url:
      defaultZone: http://${eureka.instance.hostname}:7001/eureka/,http://eureka7002.com/eureka/,http://eureka7003.com/eureka/ #与Eureka注册服务中心的通信zone和url地址

#网关配置
zuul:
  ignored-services: "*" # 通配符 * , 隐藏全部的!访问原来provider-crud不能访问ignored:忽略
  prefix: /kun #加上统一的前缀!kun,否则,就访问不了了
  routes:
    myclent.serviceId: provider-crud
    myclent.path: /myprovider/**

info:
  appname: "zuul网关"
  auth: "zhoukun"

主启动类@EnableZuulProxy


@SpringBootApplication
@EnableZuulProxy
public class zuulApplication {

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

启动

在这里插入图片描述
测试

http://localhost:9527/myprovider/query
http://localhost:9527/provider-crud/query

原真实服务名忽略

ignored-services: "*" # 通配符 * , 隐藏全部的!访问原来provider-crud不能访问ignored:忽略

设置统一公共前缀

 prefix: /kun #加上统一的前缀!kun,否则,就访问不了了

http://localhost:9527/kun/myprovider/query

练习地址

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值