Hystrix(服务熔断,服务降级)

一、Hystrix

1、服务雪崩

       多个微服务之间调用的时候,假设微服务A调用微服务B和微服务C,微服务B和微服务C有调用其他的微服务,这就是所谓的”扇出”,如扇出的链路上某个微服务的调用响应式过长或者不可用,对微服务A的调用就会占用越来越多的系统资源,进而引起系统雪崩,所谓的”雪崩效应”。

2、Hystrix

       Hystrix是一个用于分布式系统的延迟容错的开源库。在分布式系统里,许多依赖不可避免的调用失败,比如超时、异常等,Hystrix能够保证在一个依赖出问题的情况下,不会导致整个服务失败,避免级联故障,以提高分布式系统的弹性

        “断路器”本身是一种开关装置,当某个服务单元发生故障监控(类似熔断保险丝),向调用方法返回一个符合预期的、可处理的备选响应(FallBack),而不是长时间的等待或者抛出调用方法无法处理的异常,这样就保证了服务调用方的线程不会被长时间、不必要地占用,从而避免了故障在分布式系统中的蔓延。乃至雪崩。

二、服务熔断

        熔断机制是应对雪崩效应的一种微服务链路保护机制,

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

创建一个工程,命名为:DeptProvider8001_Hystrix_App

1、增加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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>microservicecloud</artifactId>
        <groupId>com.yufeng.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>microservicecloud-provider-dept-hystrix-8001</artifactId>

    <dependencies>
        <!-- hystrix -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>
        <!-- 将微服务provider侧注册进eureka -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <!-- 引入自己定义的api通用包,可以使用Dept部门Entity -->
        <dependency>
            <groupId>com.yufeng.springcloud</groupId>
            <artifactId>microservicecloud-api</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>

        <!-- actuator监控信息完善 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
    </dependencies>
</project>

2、yml文件修改,修改服务名称instance-id:为自己的微服务名称即可

server:
  port: 8001

mybatis:
  config-location: classpath:mybatis/mybatis.cfg.xml        # mybatis配置文件所在路径
  type-aliases-package: com.yufeng.springcloud.entities    # 所有Entity别名类所在包
  mapper-locations:
  - classpath:mybatis/mapper/**/*.xml                       # mapper映射文件

spring:
   application:
    name: microservicecloud-dept
   datasource:
    type: com.alibaba.druid.pool.DruidDataSource            # 当前数据源操作类型
    driver-class-name: org.gjt.mm.mysql.Driver              # mysql驱动包
    url: jdbc:mysql://192.168.172.20:3306/cloudDB01              # 数据库名称
    username: root
    password: root
    dbcp2:
      min-idle: 5                                           # 数据库连接池的最小维持连接数
      initial-size: 5                                       # 初始化连接数
      max-total: 5                                          # 最大连接数
      max-wait-millis: 200                                  # 等待连接获取的最大超时时间


eureka:
  client:  # 客户端注册进eureka内
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
  instance:
    instance-id: provider-hystrix-dept-8001
    prefer-ip-address: true  # 访问路径可以显示IP

info:
  app.name: yufeng-microservicecloud
  company.name: www.yufeng.com
  build.artifactId: $project.artifactId$
  build.version: $project.version$

3、增加熔断机制(@HystrixCommand

@RestController
public class DeptController
{
    @Autowired
    private DeptService service;

    @RequestMapping(value = "/dept/add", method = RequestMethod.POST)
    public boolean add(@RequestBody Dept dept)
    {
        return service.add(dept);
    }

    @RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
//一旦调用服务方法失败抛出“错误信息后,胡自动范湖用@HystrixCommand标注好的fallbackMethod调用类中的指定方法” @HystrixCommand(fallbackMethod
= "processHystrixGet") public Dept get(@PathVariable("id") Long id) { Dept dept = service.get(id); //模拟异常 if(null == dept) { throw new RuntimeException("该id的信息不存在! id=" + id); } return service.get(id); } public Dept processHystrixGet(@PathVariable("id") Long id) { return new Dept().setDname("id没有对应的信息, null -- @HystrixCommand, id=" + id) .setDb_source("no this database in MySQL."); } }

4、主启动类添加注解 @EnableCircuitBreaker

添加此注解告诉主启动类对Hystrix的支持

@SpringBootApplication
@EnableEurekaClient     //本服务启动后自动注册到eureka中
@EnableCircuitBreaker   //对hystrixR熔断机制的支持
public class DeptProvider8001_Hystrix_App
{
    public static void main(String[] args)
    {
        SpringApplication.run(DeptProvider8001_Hystrix_App.class, args);
    }
}

5、测试:

(1)启动 3个eureka服务:EurekaServer7001、EurekaServer7002、EurekaServer7003;

(2)启动 DeptProvider8001_Hystrix_App 服务

(3)最后启动DeptConsumer80_App 服务。

(4)测试地址:

http://localhost/consumer/dept/get/2

http://localhost/consumer/dept/get/112

 三、服务降级

服务降级的处理是在客户端完成的,与服务端没有关系。

整体资源快不够用了,忍痛将某些服务先关掉,待度过难关,再回来开启。

所谓降级,就是一般是从整体符合考虑,就是当某个服务熔断之后,服务器将不再被调用,此刻客户端可以自己准备一个本地的fallback回调,返回一个缺省值,这样做,虽然服务水平下降,但好歹可用,比直接挂掉要强。

1、修改消费者服务接口的提供者项目(microservicecloud-api),让service接口实现一个FallbackFactory接口类DeptClientServiceFallbackFactory(千万记得增加 @Component  注解);

注意:直接在接口定义的熔断机制中进行服务熔断,之前在controller上的@HystrixCommand(fallbackMethod=”methodName”)将弃用

import com.yufeng.springcloud.entities.Dept;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;
import java.util.List;

@Component
public class DeptClientServiceFallbackFactory implements FallbackFactory<DeptClientService>
{
    @Override
    public DeptClientService create(Throwable throwable)
    {
        return new DeptClientService() {
            @Override
            public boolean add(Dept dept)
            {
                return false;
            }

            @Override
            public Dept get(Long id)
            {
                Dept dept = new Dept();
                dept.setDeptno(id);
                dept.setDname("该ID:" + id + "没有对应的信息,Consumer客户端提供的信息,此服务Provider已关闭");
                dept.setDb_source("no this database in mysql");
                return dept;
            }

            @Override
            public List<Dept> list()
            {
                return null;
            }
        };
    }
}

2、修改提供服务的service熔断处理的机制

此处是在公共的service对某个service的方法访问出现异常后进行统一的fallback处理,即在 DeptClientService接口在注解@FeignClient 中添加 fallbackFactory 属性值,该属性赋值为实现FallbcakFactory接口的异常处理类

import com.yufeng.springcloud.entities.Dept;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;

@FeignClient(value = "microservicecloud-dept", fallbackFactory = DeptClientServiceFallbackFactory.class)
public interface DeptClientService
{
    @RequestMapping(value = "/dept/add", method = RequestMethod.POST)
    public boolean add(@RequestBody Dept dept);

    @RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
    public Dept get(@PathVariable("id") Long id);

    @RequestMapping(value = "/dept/get/list", method = RequestMethod.GET)
    public List<Dept> list();
}

3、在消费者工程(microservicecloud-consumer-dept-feign的yml文件增加如下内容,开启feign中的hystrix

feign:
  hystrix:
    enabled: true

4、将 microservicecloud-api 工程重新打包,执行: mvn clean install

5、测试

(1)启动3个 eureka 服务;

(2)启动 microservicecloud-provider-dept-8001 服务;

(3)启动 microservicecloud-consumer-dept-feign 服务;

(4)在浏览器中访问:http://localhost/consumer/dept/get/1

(5)将 microservicecloud-provider-dept-8001 服务关闭,浏览器访问:http://localhost/consumer/dept/get/1

原文地址:https://www.cnblogs.com/yufeng218/p/11042555.html