熔断器Hystrix及服务监控Dashboard

Hystrix介绍

在这里插入图片描述
hystrix对应的中文名字是“豪猪”,豪猪周身长满了刺,能保护自己不受天敌的伤害,代表了一种防御机制,这与hystrix本身的功能不谋而合,因此Netflix团队将该框架命名为Hystrix,并使用了对应的卡通形象做作为logo。

Hystrix是什么?

在分布式系统,我们一定会依赖各种服务,那么这些个服务一定会出现失败的情况,Hystrix就是这样的一个工具,它通过提供了逻辑上延时和错误容忍的解决力来协助我们完成分布式系统的交互。Hystrix 通过分离服务的调用点,阻止错误在各个系统的传播,并且提供了错误回调机制,这一系列的措施提高了系统的整体服务弹性。

Hystrix 的作用:
1,保护系统间的调用延时以及错误,特别是通过第三方的工具的网络调用
2,阻止错误在分布式系统之前的传播
3,快速失败和迅速恢复
4,错误回退和优雅的服务降级

引用场景来讲,
当一个请求依赖多个服务的时候:
正常情况下的访问
在这里插入图片描述
但是,当请求的服务中出现无法访问、异常、超时等问题时(图中的I),那么用户的请求将会被阻塞。

在这里插入图片描述
如果多个用户的请求中,都存在无法访问的服务,那么他们都将陷入阻塞的状态中。
在这里插入图片描述
这也就是服务雪崩效应。

所以Hystrix的引入,可以通过服务熔断和服务降级来解决这个问题。

测试

在一个分布式系统里,许多依赖不可避免的会调用失败,比如超时、异常等,如何能够保证在一个依赖出问题的情况下,不会导致整体服务失败,这个就是Hystrix需要做的事情。Hystrix提供了熔断、隔离、Fallback、cache、监控等功能,能够在一个、或多个依赖同时出现问题时保证系统依然可用。

Hystrix服务熔断服务降级@HystrixCommand fallbackMethod

熔断机制是应对雪崩效应的一种微服务链路保护机制。
当某个服务不可用或者响应时间超时,会进行服务降级,进而熔断该节点的服务调用,快速返回自定义的错误影响页面信息。

下面我针对应对雪崩效应使用Hystrix进行测试一下:

(有不明白的请查看我的上篇博客)
(还需要注意的是我这里测试的是单机模式的)

首先创建一个新的带服务熔断的服务提供者项目
microservice-student-provider-hystrix-1004

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.zlk</groupId>
        <artifactId>springcloud</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>microservice-student-provider-hystrix-1004</artifactId>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.zlk</groupId>
            <artifactId>microservice-common</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>
        <!--  修改后立即生效,热部署  -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>springloaded</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>com.zlk</groupId>
            <artifactId>microservice-common</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>compile</scope>
        </dependency>

        <!--添加注册中心Eureka相关配置-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </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>

        <!--Hystrix相关依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>
        
    </dependencies>

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

</project>

yml:

server:
  port: 1004
  context-path: /
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/t224?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  application:
    name: microservice-student
  profiles: provider-hystrix-1004

eureka:
  instance:
    hostname: localhost
    appname: microservice-student
    instance-id: microservice-student:1004
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://eureka2001.zlk.com:2001/eureka/,http://eureka2002.zlk.com:2002/eureka/,http://eureka2003.zlk.com:2003/eureka/

info:
  groupId: com.zlk.springcloud
  artifactId: microservice-student-provider-hystrix-1004
  version: 1.0-SNAPSHOT
  userName: http://zlk.com
  phone: 123456

启动类:
@EnableCircuitBreaker

package com.zlk.microservicestudentproviderhystrix1004;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@EnableCircuitBreaker
@EntityScan("com.zlk.*.*")
@EnableEurekaClient
@SpringBootApplication
public class MicroserviceStudentProviderHystrix1004Application {

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

}

再添加一个controller,
添加之前先把之前的服务端的repository 和service包copy过来,

package com.zlk.microservicestudentproviderhystrix1004.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zlk.microservicecommon.entity.Student;
import com.zlk.microservicestudentproviderhystrix1004.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/student")
public class StudentProviderController {
 
    @Autowired
    private StudentService studentService;
    @Value("${server.port}")
    private String port;
     
    @PostMapping(value="/save")
    public boolean save(Student student){
        try{
            studentService.save(student);  
            return true;
        }catch(Exception e){
            return false;
        }
    }
     
    @GetMapping(value="/list")
    public List<Student> list(){
        return studentService.list();
    }
     
    @GetMapping(value="/get/{id}")
    public Student get(@PathVariable("id") Integer id){
        return studentService.findById(id);
    }
     
    @GetMapping(value="/delete/{id}")
    public boolean delete(@PathVariable("id") Integer id){
        try{
            studentService.delete(id);
            return true;
        }catch(Exception e){
            return false;
        }
    }

    @RequestMapping("/ribbon")
    public String ribbon(){
        return "工号【"+port+"】正在为您服务";
    }

    /**
     * 测试Hystrix服务降级
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @GetMapping(value="/hystrix")
    @HystrixCommand(fallbackMethod="hystrixFallback")
    public Map<String,Object> hystrix() throws InterruptedException{
//        Thread.sleep(2000);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("code", 200);
        map.put("info","工号【"+port+"】正在为您服务");
        return map;
    }

    public Map<String,Object> hystrixFallback() throws InterruptedException{
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("code", 500);
        map.put("info", "系统【"+port+"】繁忙,稍后重试");
        return map;
    }
}

主要的是hystrix()和hystrixFallback()方法,
hystrix()方法上的@HystrixCommand(fallbackMethod=“hystrixFallback”)注解的意思是:
表明这个方法我们在没有异常以及没有超时(hystrix默认1秒算超时)的情况,才返回正常的业务数据;

fallbackMethod是指定后退的方法,也就是当这个方法出现问题,会执行哪个方法。

且这之中的 Thread.sleep(2000);我注解了,他是用来模拟响应超时的。

别忘了,消费者那边也得加上这些方法来测试、

先开eureka服务器,然后再开生产者,再开消费者。

结果:
(因为我测试的是单机的所以还是存在轮询的问题,多刷几遍即可)

可以看到这是我开了线程睡眠的结果:
在这里插入图片描述

Hystrix默认超时时间设置

Hystrix默认超时时间是1秒,我们可以通过hystrix源码看到:
按ctrl+shift+R 填入HystrixCommandProperties
也可以找到 hystrix-core.jar com.netflix.hystrix包下的HystrixCommandProperties类。

在这里插入图片描述
因为在某些正常操作情况下,处理时间会超过1秒,所以这种不太合理,需要自己来改变超时时常。
那么怎么改呢?
在yml文件中添加:

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 3000

以毫秒为单位,我这里写的是3秒。
再次运行测试,即可出现效果。

Hystrix服务监控Dashboard

Hystrix提供了 准实时的服务调用监控项目Dashboard,能够实时记录通过Hystrix发起的请求执行情况,

要实现这个,需要重新新建一个项目:
microservice-student-consumer-hystrix-dashboard-90
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.zlk</groupId>
        <artifactId>springcloud</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>microservice-student-consumer-hystrix-dashboard-90</artifactId>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--Hystrix服务监控Dashboard依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>

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

</project>

yml:

server:
  port: 90
  context-path: /

启动类:

package com.zlk.microservicestudentconsumerhystrixdashboard90;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;

@EnableHystrixDashboard
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class MicroserviceStudentConsumerHystrixDashboard90Application {

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

}

启动项目,

浏览器输入:http://localhost:90/hystrix
进入以下界面即说明成功:
在这里插入图片描述
我们在启动eureka和microservice-student-provider-hystrix-1004,也就是用了hystrix技术的生产者。再启动消费者。

然后我们在以下的方框中加入:
http://localhost:1004/hystrix.stream
也就是输入监控地址:本地IP的1004端口,
Delay则代表的是两秒刷新一次监控页面。
在这里插入图片描述
输入完点击 Monitor Stream按钮进入以下界面:

在这里插入图片描述
指标含义:
在这里插入图片描述
当你的端口接收到什么eureka请求的状态都会显示在这里。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值