熔断器Hystrix及服务监控Dashboard

服务雪崩效应

当一个请求依赖多个服务的时候:

正常情况下的访问
在这里插入图片描述
但是 当请求的服务中出现无法访问、异常、超时等问题时(图中的I),那么用户的请求将会被阻塞
在这里插入图片描述

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

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

服务熔断服务降级

Hystrix断路器简介

Hystrix对应的中文名字是“豪猪”,豪猪周身长满了刺,能保护自己不受天敌的伤害,代表了一种防御机制,这与hystrix本身的功能不谋而合,因此Netflix团队将该框架命名为Hystrix,并使用了对应的卡通形象做作为logo
在这里插入图片描述
在一个分布式系统里,许多依赖不可避免的会调用失败,比如超时、异常等,如何能够保证在一个依赖出问题的情况下,不会导致整体服务失败,这个就是Hystrix需要做的事情。Hystrix提供了熔断、隔离、Fallback、cache、监控等功能,能够在一个、或多个依赖同时出现问题时保证系统依然可用

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

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

项目测试

写一个新的带服务熔断的服务提供者项目 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.xwt</groupId>
        <artifactId>t237microservice</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.xwt</groupId>
            <artifactId>microservice-common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </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>

        <!--添加注册中心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>

② application.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/demo?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.xwt.com:2001/eureka/,http://eureka2002.xwt.com:2002/eureka/,http://eureka2003.xwt.com:2003/eureka/

info:
  groupId: com.xwt.t237microservice
  artifactId: microservice-student-provider-1001
  version: 1.0-SNAPSHOT
  userName: 宋冬野
  phone: 10016

③ 启动类StudentProviderHystrixApplication_1004加下注解支持 @EnableCircuitBreaker

package com.xwt.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.xwt.*.*")
@EnableEurekaClient
@SpringBootApplication
public class MicroserviceStudentProviderHystrix1004Application {

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

}

④ 服务提供者1004中controller新增

package com.xwt.microservicestudentproviderhystrix1004.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.xwt.microservicecommon.entity.Student;
import com.xwt.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
     */
    @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;
    }
}

⑤ microservice-student-consumer-80项目也要对应的加个方法

package com.xwt.microservicestudentconsumer80.controller;

import com.xwt.microservicecommon.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

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

@RestController
@RequestMapping("/student")
public class StudentConsumerController {

    private final static String SERVER_IP_PORT = "http://MICROSERVICE-STUDENT";
 
     @Autowired
     private RestTemplate restTemplate;
      
     @PostMapping(value="/save")
     private boolean save(Student student){
         return restTemplate.postForObject(SERVER_IP_PORT+"/student/save", student, Boolean.class);
     }
      
    @GetMapping(value="/list")
    public List<Student> list(){
        return restTemplate.getForObject(SERVER_IP_PORT+"/student/list", List.class);
    }
     
    @GetMapping(value="/get/{id}")
    public Student get(@PathVariable("id") Integer id){
        return restTemplate.getForObject(SERVER_IP_PORT+"/student/get/"+id, Student.class);
    }
     
    @GetMapping(value="/delete/{id}")
    public boolean delete(@PathVariable("id") Integer id){
        try{
            restTemplate.getForObject(SERVER_IP_PORT+"/student/delete/"+id, Boolean.class);
            return true;
        }catch(Exception e){
            return false;
        }
    }
    
    @RequestMapping("/ribbon")
    public String ribbon() {
        return restTemplate.getForObject(SERVER_IP_PORT + "/student/ribbon", String.class);
    }

    /**
     * 测试Hystrix服务降级
     * @return
     */
    @GetMapping(value="/hystrix")
    @ResponseBody
    public Map<String,Object> hystrix(){
        return restTemplate.getForObject(SERVER_IP_PORT+"/student/hystrix/", Map.class);
    }

}

⑥ 测试

先启动三个eureka,再启动带hystrix的provider,最后启动普通的consumer

这里我正常访问 返回的是 200 业务数据
在这里插入图片描述
但是我们这里当我们开启Thread.sleep(2000) 模拟超时
在这里插入图片描述
就进入我们fallback指定的本地方法 我们搞的是500 系统出错,稍后重试,有效的解决雪崩效应,以及返回给用户界面

在这里插入图片描述

Hystrix默认超时时间设置

Hystrix默认超时时间是1秒,我们可以通过hystrix源码看到

找到 hystrix-core.jar com.netflix.hystrix包下的HystrixCommandProperties类
default_executionTimeoutInMilliseconds属性局势默认的超时时间

在这里插入图片描述
默认1000毫秒 1秒

我们系统里假如要自定义设置hystrix的默认时间的话;

application.yml配置文件加上

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

改成3秒 然后 我们代码里sleep修改成2秒测试
在这里插入图片描述
测试OK
在这里插入图片描述
sleep修改成5秒
在这里插入图片描述
报错提示表示ok
在这里插入图片描述

Hystrix服务监控Dashboard

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.xwt</groupId>
        <artifactId>t237microservice</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>microservice-student-consumer-hystrix-dashboard-90</artifactId>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--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>

application.yml

server:
  port: 90
  context-path: /

启动类:StudentConsumerDashBoardApplication_90加注解:@EnableHystrixDashboard

package com.xwt.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
在这里插入图片描述
出现这个 就说明OK

启动三个eureka 然后再启动microservice-student-provider-hystrix-1004

我们直接请求http://localhost:1004/student/hystrix
返回正常业务

监控http://localhost:1004/hystrix.stream 这个路径即可
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Cloud Hystrix是一个开源的容错框架,提供了断路模式的实现,可以防止分布式系统中的级联故障。除此之外,它还包含服务降级、服务熔断服务限流和监控报警等功能。下面分别用代码展示这些功能的实现。 1. 断路模式 ```java @HystrixCommand(fallbackMethod = "fallback") public String hello() { // 调用其他服务或者一些耗时操作 } public String fallback() { return "Sorry, the service is unavailable!"; } ``` 在上面的代码中,`@HystrixCommand`注解标记的方法会被Hystrix包装成一个独立的线程池中的可执行命令。当执行命令的线程池达到一定阈值时,Hystrix会自动断开服务调用,避免级联故障。 2. 服务降级 ```java @HystrixCommand(fallbackMethod = "fallback") public String hello() { // 调用其他服务或者一些耗时操作 } public String fallback() { return "Sorry, the service is unavailable!"; } ``` 在上面的代码中,当调用`hello()`方法失败时,Hystrix会自动调用`fallback()`方法,返回一个默认的响应结果。 3. 服务熔断 ```java @HystrixCommand(fallbackMethod = "fallback", commandProperties = { @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000") }) public String hello() { // 调用其他服务或者一些耗时操作 } public String fallback() { return "Sorry, the service is unavailable!"; } ``` 在上面的代码中,我们使用`@HystrixCommand`注解的`commandProperties`属性来配置熔断的阈值和休眠窗口。当调用`hello()`方法的失败率达到一定阈值时,Hystrix会自动触发熔断,避免级联故障。 4. 服务限流 ```java @HystrixCommand(fallbackMethod = "fallback", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"), @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50") }) public String hello() { // 调用其他服务或者一些耗时操作 } public String fallback() { return "Sorry, the service is unavailable!"; } ``` 在上面的代码中,我们使用`@HystrixCommand`注解的`commandProperties`属性来配置服务限流的参数。当调用`hello()`方法超时或者失败率达到一定阈值时,Hystrix会自动限制服务的请求速率,保护服务资源。 5. 监控报警 ```java @SpringBootApplication @EnableHystrix @EnableHystrixDashboard public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 在上面的代码中,我们使用`@EnableHystrix`和`@EnableHystrixDashboard`注解来启用Hystrix监控和报警功能。通过访问Hystrix Dashboard,可以实时监控服务的健康状态,及时发现问题并进行处理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值