SpringCloud Netflix Hystrix

一、 Hystrix简介

1 什么是灾难性雪崩效应

在这里插入图片描述

造成灾难性雪崩效应的原因,可以简单归结为下述三种:

1.服务提供者不可用。如:硬件故障、程序BUG、缓存击穿、并发请求量过大等。
2.重试加大流量。如:用户重试、代码重试逻辑等。
3.服务调用者不可用。如:同步请求阻塞造成的资源耗尽等。

雪崩效应最终的结果就是:

服务链条中的某一个服务不可用,导致一系列的服务不可用,最终造成服务逻辑崩溃。这种问题造成的后果,往往是无法预料的。
解决灾难性雪崩效应的方式通常有:降级、熔断和请求缓存。

2 什么是Hystrix

Hystrix是Netflix开源的一款容错框架,具有自我保护能力。为了实现容错和自我保护。

Hystrix设计目标:

1、 对来自依赖的延迟和故障进行防护和控制——这些依赖通常都是通过网络访问的
2、 阻止故障的连锁反应
3、 快速失败并迅速恢复
4、 回退并优雅降级
5、 提供近实时的监控与告警

Hystrix遵循的设计原则:

1、 防止任何单独的依赖耗尽资源(线程)
2、 过载立即切断并快速失败,防止排队
3、 尽可能提供回退以保护用户免受故障
4、 使用隔离技术(例如隔板,泳道和断路器模式)来限制任何一个依赖的影响
5、 通过近实时的指标,监控和告警,确保故障被及时发现
6、 通过动态修改配置属性,确保故障及时恢复
7、 防止整个依赖客户端执行失败,而不仅仅是网络通信

Hystrix如何实现这些设计目标?

1、 使用命令模式将所有对外部服务(或依赖关系)的调用包装在HystrixCommand或HystrixObservableCommand对象中,并将该对象放在单独的线程中执行;
2、 每个依赖都维护着一个线程池(或信号量),线程池被耗尽则拒绝请求(而不是让请求排队)。
3、 记录请求成功,失败,超时和线程拒绝。
4、 服务错误百分比超过了阈值,熔断器开关自动打开,一段时间内停止对该服务的所有请求。
5、 请求失败,被拒绝,超时或熔断时执行降级逻辑。
6、 近实时地监控指标和配置的修改。

 <!-- 在Spring cloud中处理服务雪崩效应,都需要依赖hystrix组件。在Application Client应用的pom文件中都需要引入下述依赖: -->
 <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>

二、 服务降级(Ribbon中)

降级是指,当(请求超时、资源不足等情况)发生时进行服务降级处理,不调用真实服务逻辑,而是使用快速失败(fallback)方式直接返回一个托底数据,保证服务链条的完整,避免服务雪崩。
解决服务雪崩效应,都是避免application client请求application service时,出现服务调用错误或网络问题。处理手法都是在application client中实现。我们需要在application client相关工程中导入hystrix依赖信息。并在对应的启动类上增加新的注解@EnableCircuitBreaker,这个注解是用于开启hystrix熔断器的,简言之,就是让代码中的hystrix相关注解生效。

具体实现过程如下:

1 修改application service 中的service代码

修改application service工程中的代码,模拟超时错误。此模拟中,让服务端代码返回之前休眠2000毫秒,替代具体的复杂服务逻辑。

    @RequestMapping("/user/save")
    @ResponseBody
    public Map<String, Object> save(User user){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("新增用户数据: " + user);
        Map<String, Object> result = new HashMap<>();
        result.put("code", "200"); // 返回的状态码
        result.put("message", "新增用户成功"); // 返回的处理结果消息。
        return result;
    }
}

2 application client POM依赖添加

	<dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>

3 application client容错处理代码

	/**
     * 远程方法调用。访问application service,访问的地址是:http://localhost:8080/user/save
     * HystrixCommand注解 - Hystrix容灾处理注解。当前方法做容灾处理。
     *  属性fallbackMethod - 如果远程调用发生问题,调用本地的什么方法获取降级结果(托底)。
     */
	@Override
    @HystrixCommand(fallbackMethod = "saveFallback")
    public Map<String, Object> save(User user) {
        // 根据服务的名称,获取服务实例。服务名称就是配置文件yml中的spring.application.name
        // 服务实例包括,这个名称的所有服务地址和端口。
        ServiceInstance instance =
                this.loadBalancerClient.choose("ribbon-app-service");
        // 访问地址拼接
        StringBuilder builder = new StringBuilder("");
        builder.append("http://").append(instance.getHost())
                .append(":").append(instance.getPort()).append("/user/save")
                .append("?username=").append(user.getUsername())
                .append("&password=").append(user.getPassword())
                .append("&remark=").append(user.getRemark());
        System.out.println("本地访问地址:" + builder.toString());

        // 创建一个Rest访问客户端模板对象。
        RestTemplate template = new RestTemplate();

        // 约束响应结果类型
        ParameterizedTypeReference<Map<String, Object>> responseType =
                new ParameterizedTypeReference<Map<String, Object>>() {
                };

        // 远程访问application service。
        ResponseEntity<Map<String, Object>> response =
                template.exchange(builder.toString(), HttpMethod.GET,
                null, responseType);

        Map<String, Object> result = response.getBody();
        return result;
    }

	private Map<String, Object> saveFallback(User user){
        // 同步->异步,讲user封装成message消息,发送到RabbitMQ中。
        System.out.println("saveFallback方法执行:" + user);
        Map<String, Object> result = new HashMap<>();
        result.put("message", "服务器忙,请稍后重试!");
        return result;
    }

4 application client配置文件application.yml

server:
  port: 8081

spring:
  application:
    name: ribbon-app-client

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/


ribbon-app-service: # 远程访问这个命名的服务
  ribbon: # 底层Ribbon配置
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule # 就是具体的负载均衡策略类型全名
    # listOfServers: localhost:8080  # 多个地址用逗号分隔。

hystrix: # 配置Hystrix相关信息
  command: # 配置HystrixCommand相关内容
    default: # 所有范围
      execution:
        timeout:
          enabled: true # 使用Hystrix作为超时判定机制
        isolation:
          thread:
            timeoutInMilliseconds: 1000  # 具体的超时时间

5 application client启动类

package com.bjsxt.userclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;

/**
 * EnableCircuitBreaker注解除了开启Hystrix容灾处理机制(扫描HystrixCommand注解)外,
 * 还会开启Hystrix相关的数据监控服务。
 */
@SpringBootApplication
@EnableCircuitBreaker
public class RibbonAppClientApp {
    public static void main(String[] args) {
        SpringApplication.run(RibbonAppClientApp.class, args);
    }
}

三、 服务熔断(Ribbon中)(服务降级的强化版)

当一定时间内,异常请求比例(请求超时、网络故障、服务异常等)达到阀值时,启动熔断器,熔断器一旦启动,则会停止调用具体服务逻辑,通过fallback快速返回托底数据,保证服务链的完整。
熔断有自动恢复机制,如:当熔断器启动后,每隔5秒,尝试将新的请求发送给服务提供者,如果服务可正常执行并返回结果,则关闭熔断器,服务恢复。如果仍旧调用失败,则继续返回托底数据,熔断器持续开启状态。

在这里插入图片描述

具体实现过程如下:(-----在服务降级的基础上只需要修改application client容错处理代码的注解-----)

application client容错处理代码

/**
     * 远程方法调用。访问application service,访问的地址是:http://localhost:8080/user/save
     * HystrixCommand注解 - Hystrix容灾处理注解。当前方法做容灾处理。
     *  属性fallbackMethod - 如果远程调用发生问题,调用本地的什么方法获取降级结果(托底)。
     *  属性commandProperties - 定义Hystrix容灾逻辑的具体参数。
     *    CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD - 单位时间内,多少个请求发生错误(默认值10),开启
     *      熔断(断路由)
     *    CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE - 单位时间内,错误请求百分比,开启
     *      熔断(断路由)
     *    CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS - 断路由开启后,休眠多少毫秒(默认值5000),不访问
     *      远程服务。
     */
    @Override
    @HystrixCommand(fallbackMethod = "saveFallback", commandProperties = {
        @HystrixProperty(
                name=HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD,
                value="10"
        ),
        @HystrixProperty(
                name=HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE,
                value="50"
        ),
        @HystrixProperty(
                name=HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS,
                value="3000"
        )
    })
    public Map<String, Object> save(User user) {
        // 根据服务的名称,获取服务实例。服务名称就是配置文件yml中的spring.application.name
        // 服务实例包括,这个名称的所有服务地址和端口。
        ServiceInstance instance =
                this.loadBalancerClient.choose("ribbon-app-service");
        // 访问地址拼接
        StringBuilder builder = new StringBuilder("");
        builder.append("http://").append(instance.getHost())
                .append(":").append(instance.getPort()).append("/user/save")
                .append("?username=").append(user.getUsername())
                .append("&password=").append(user.getPassword())
                .append("&remark=").append(user.getRemark());
        System.out.println("本地访问地址:" + builder.toString());

        // 创建一个Rest访问客户端模板对象。
        RestTemplate template = new RestTemplate();

        // 约束响应结果类型
        ParameterizedTypeReference<Map<String, Object>> responseType =
                new ParameterizedTypeReference<Map<String, Object>>() {
                };

        // 远程访问application service。
        ResponseEntity<Map<String, Object>> response =
                template.exchange(builder.toString(), HttpMethod.GET,
                null, responseType);

        Map<String, Object> result = response.getBody();
        return result;
    }

    private Map<String, Object> saveFallback(User user){
        // 同步->异步,讲user封装成message消息,发送到RabbitMQ中。
        System.out.println("saveFallback方法执行:" + user);
        Map<String, Object> result = new HashMap<>();
        result.put("message", "服务器忙,请稍后重试!");
        return result;
    }

四、 请求缓存(Ribbon中)(不推荐)(查询频率高,修改频率低时谨慎使用)

请求缓存:通常意义上说,就是将同样的GET请求结果缓存起来,使用缓存机制(如redis、mongodb)提升请求响应效率。
使用请求缓存时,需要注意非幂等性操作对缓存数据的影响。
请求缓存是依托某一缓存服务来实现的。在案例中使用redis作为缓存服务器,那么可以使用spring-data-redis来实现redis的访问操作。

1 修改application service代码(增加get和post方法)

package com.bjsxt.userservice.controller;

import com.bjsxt.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * 提供服务的控制器
 */
@Controller
public class UserController {
    @GetMapping("/post")
    @ResponseBody
    public Map<String, Object> post(){
        System.out.println("post method run");
        Map<String, Object> result = new HashMap<>();
        result.put("message", "post方法执行成功");
        return result;
    }

    @GetMapping("/get")
    @ResponseBody
    public Map<String, Object> get(){
        System.out.println("get method run");
        Map<String, Object> result = new HashMap<>();
        result.put("message", "get方法执行成功");
        return result;
    }

    @RequestMapping("/user/save")
    @ResponseBody
    public Map<String, Object> save(User user){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("新增用户数据: " + user);
        Map<String, Object> result = new HashMap<>();
        result.put("code", "200"); // 返回的状态码
        result.put("message", "新增用户成功"); // 返回的处理结果消息。
        return result;
    }
}

2 application client POM依赖添加

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

3 application client 容错处理代码

package com.bjsxt.userclient.service.impl;

import com.bjsxt.entity.User;
import com.bjsxt.userclient.service.UserService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

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

/**
 * cacheNames - 可以实现缓存分组,是Hystrix做分组。
 * 
 * @CacheConfig(cacheNames = "test_cache_names")
 * 在类上,增加@CacheConfig注解,用来描述当前类型可能使用cache缓存。
 * 如果使用缓存,则缓存数据的key的前缀是cacheNames。
 * cacheNames是用来定义一个缓存集的前缀命名的,相当于分组。
 */
@Service
@CacheConfig(cacheNames = "test_cache_names")
public class UserServiceImpl implements UserService {

    @Autowired
    private LoadBalancerClient loadBalancerClient;
    
    /**
     * 查询,只要路径和参数不变,理论上查询结果不变。可以缓存,提升查询效率。
     * @return
     */
    @Cacheable("springcloud_cache")
    public Map<String, Object> get(){
        ServiceInstance instance = this.loadBalancerClient.choose("ribbon-app-service");
        StringBuilder builder = new StringBuilder("");
        builder.append("http://").append(instance.getHost())
                .append(":").append(instance.getPort())
                .append("/get");
        System.out.println(builder.toString());
        RestTemplate template = new RestTemplate();
        ParameterizedTypeReference<Map<String, Object>> type =
                new ParameterizedTypeReference<Map<String, Object>>() {
                };
        ResponseEntity<Map<String, Object>> responseEntity =
                template.exchange(builder.toString(), HttpMethod.GET, null, type);
        return responseEntity.getBody();
    }

    /**
     * 写操作,数据写操作执行后,缓存数据失效,应该清理缓存。
     * @return
     */
    @CacheEvict("springcloud_cache")
    public Map<String, Object> post(){
        ServiceInstance instance = this.loadBalancerClient.choose("ribbon-app-service");
        StringBuilder builder = new StringBuilder("");
        builder.append("http://").append(instance.getHost())
                .append(":").append(instance.getPort())
                .append("/post");
        System.out.println(builder.toString());
        RestTemplate template = new RestTemplate();
        ParameterizedTypeReference<Map<String, Object>> type =
                new ParameterizedTypeReference<Map<String, Object>>() {
                };
        ResponseEntity<Map<String, Object>> responseEntity =
                template.exchange(builder.toString(), HttpMethod.GET, null, type);
        return responseEntity.getBody();
    }
}

4 application client 配置文件application.yml

server:
  port: 8082

spring:
  application:
    name: ribbon-app-client
  redis: # spring-data-redis配置信息
    host: 192.168.14.129 # 访问的redis地址, 默认localhost
    port: 6379 # redis的端口,默认6379
    database: 0  # 访问的redis的数据库编号, 默认0

eureka:
  client:
    service-url:
      defaultZone:
        - http://localhost:8761/eureka/

ribbon-app-service: # 远程访问这个命名的服务
  ribbon: # 底层Ribbon配置
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule # 就是具体的负载均衡策略类型全名
    # listOfServers: localhost:8080  # 多个地址用逗号分隔。

hystrix: # 配置Hystrix相关信息
  command: # 配置HystrixCommand相关内容
    default: # 所有范围
      execution:
        timeout:
          enabled: true # 使用Hystrix作为超时判定机制
        isolation:
          thread:
            timeoutInMilliseconds: 1000  # 具体的超时时间

5 application client 启动类(加@EnableCaching注解)

package com.bjsxt.userclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;

/**
 * EnableCircuitBreaker注解除了开启Hystrix容灾处理机制(扫描HystrixCommand注解)外,
 * 还会开启Hystrix相关的数据监控服务。
 */
@SpringBootApplication
@EnableCircuitBreaker
@EnableCaching
public class RibbonAppClientApp {
    public static void main(String[] args) {
        SpringApplication.run(RibbonAppClientApp.class, args);
    }
}

五、 Openfeign的雪崩处理

在声明式远程服务调用Openfeign中,实现服务灾难性雪崩效应处理也是通过Hystrix实现的。而feign启动器spring-cloud-starter-openfeign中是包含Hystrix相关依赖的。如果只使用服务降级功能不需要做独立依赖。如果需要使用Hystrix其他服务容错能力,需要依赖spring-cloud-starter-netflix-hystrix资源。从Dalston版本后,feign默认关闭Hystrix支持。所以必须在全局配置文件中开启feign技术中的Hystrix支持。具体实现如下:

1 服务降级

1.1 POM依赖

Openfeign的启动器依赖spring-cloud-starter-openfeign中,自带Hystrix处理相关依赖,如果只使用服务降级功能不需要做独立依赖,通过配置即可开启容错处理机制

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

1.2 application client 服务接口

package com.bjsxt.feign.client.service;

import com.bjsxt.feign.api.UserServiceAPI;
import com.bjsxt.feign.client.service.impl.UserServiceImpl;
import org.springframework.cloud.openfeign.FeignClient;

/**
 * 本地服务,是用于远程访问Application Service的本地服务接口。
 */
@FeignClient(value="feign-app-service", fallback = UserServiceImpl.class)
public interface UserService extends UserServiceAPI {
}

1.3 application client 服务接口实现

package com.bjsxt.feign.client.service.impl;

import com.bjsxt.feign.client.service.UserService;
import com.bjsxt.feign.entity.User;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import org.springframework.stereotype.Service;

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

/**
 * 本地接口的实现类
 * 实现类中的每个方法,都是其对应的远程调用服务的降级方法。
 */
@Service
public class UserServiceImpl implements UserService {
    @Override
    public Map<String, Object> saveUser(User user) {
        Map<String, Object> result = new HashMap<>();
        result.put("message", "saveUser方法容错处理。");
        return result;
    }

    @Override
    public Map<String, Object> updateUser(User user) {
        Map<String, Object> result = new HashMap<>();
        result.put("message", "updateUser方法容错处理。");
        return result;
    }
}

1.4 application client 配置文件application.yml 添加

超时管理默认ribbon管理,使用hystrix后由hystrix管理(所以还需配置超时管理)

feign:
  hystrix:
    enabled: true

hystrix:
  command:
    default:
      execution:
        timeout:
          enable: true
        isolation:
          thread:
            timeoutInMilliseconds: 1000

1.5 applicaiton client 启动类(不需要改)

package com.bjsxt.feign.client;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.openfeign.EnableFeignClients;

/**
 * 需要提供一个新的注解
 * @EnableFeignClients - 开启OpenFeign客户端技术。扫描@FeignClient注解。
 *   默认扫描当前类所在包,及子包中所有的类型。
 *
 */
@SpringBootApplication
@EnableCircuitBreaker
@EnableFeignClients(basePackages = {"com.bjsxt.feign.client.service"})
public class FeignClientApp {
    public static void main(String[] args) {
        SpringApplication.run(FeignClientApp.class, args);
    }
}

2 服务熔断

服务降级的升级版,只需要在服务降级的基础上修改配置文件即可

hystrix:
  command:
    default:
      execution:
        timeout:
          enable: true
        isolation:
          thread:
            timeoutInMilliseconds: 1000
      fallback:
        enable: true # 是否开启服务降级处理。默认开启。
      circuitBreaker:
        enable: true # 是否开启熔断机制。 默认开启。
        requestVolumeThreshold: 3 # 单位时间内,错误多少次请求,开启熔断
        sleepWindowInMilliseconds: 3000  # 开启熔断口,多少毫秒不访问远程服务
        errorThresholdPercentage: 50 # 单位时间内,错误率达到多少,开启熔断
        forceOpen: false # 是否强制开启熔断,永远不访问远程服务。默认false
        forceClosed: false # 是否强制关闭熔断,永远访问远程服务。默认false

六、 可视化的数据监控Hystrix-dashboard(近实时监控)

Hystrix Dashboard是一款针对Hystrix进行实时监控的工具,通过Hystrix Dashboard我们可以在直观地看到各Hystrix Command的请求响应时间, 请求成功率等数据。

1 Ribbon中数据监控

1.1 POM依赖

Hystrix Dashboard是针对Hystrix容错处理相关数据的监控工具。只要在使用了Hystrix技术的应用工程中导入对应依赖即可。

注意:

如果在Openfeign技术中开启Hystrix Dashboard监控,则需要将spring-cloud-starter-netflix-hystrix启动器导入POM文件,否则无法在启动类上使用@EnableCircuitBreaker注解。
启动类上必须使用@EnableCircuitBreaker注解

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!-- cloud中监控数据是使用boot提供的actuator实现的。 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>

1.2 配置文件application.yml

management:
  endpoints:
    web:
      exposure:
        include:
          - info
          - health
          - hystrix.stream

1.3 启动类
(localhost:8080/actuator查看(localhost:8080/actuator/hystrix.stream))

package com.bjsxt.userclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;

/**
 * 如果要使用Hystrix Dashboard做近实时监控的话,启动类上必须使用EnableCircuitBreaker
 * 注解描述。
 * EnableCircuitBreaker注解除了开启Hystrix容灾处理机制(扫描HystrixCommand注解)外,
 * 还会开启Hystrix相关的数据监控服务。
 */
@SpringBootApplication
@EnableCircuitBreaker
@EnableCaching
public class RibbonAppClientApp {
    public static void main(String[] args) {
        SpringApplication.run(RibbonAppClientApp.class, args);
    }
}

2 openfeign 中数据监控

2.1 POM依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!-- cloud中监控数据是使用boot提供的actuator实现的。 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>

2.2 application.yml 配置

management:
  endpoints:
    web:
      exposure:
        include:
          - info
          - health
          - hystrix.stream

2.3 启动类加 @EnableCircuitBreaker注解
(localhost:8080/actuator查看(localhost:8080/actuator/hystrix.stream))

package com.bjsxt.feign.client;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.openfeign.EnableFeignClients;

/**
 * 需要提供一个新的注解
 * @EnableFeignClients - 开启OpenFeign客户端技术。扫描@FeignClient注解。
 *   默认扫描当前类所在包,及子包中所有的类型。
 *
 * EnableHystrixDashboard注解 - 开启HystrixDashboard提供的可视化界面。
 */
@SpringBootApplication
@EnableCircuitBreaker
@EnableFeignClients(basePackages = {"com.bjsxt.feign.client.service"})
public class FeignClientApp {
    public static void main(String[] args) {
        SpringApplication.run(FeignClientApp.class, args);
    }
}

3 可视化监控

3.1 启动类加 @EnableHystrixDashboard注解
(localhost:8081/hystrix 查看)

package com.bjsxt.feign.client;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.openfeign.EnableFeignClients;

/**
 * 需要提供一个新的注解
 * @EnableFeignClients - 开启OpenFeign客户端技术。扫描@FeignClient注解。
 *   默认扫描当前类所在包,及子包中所有的类型。
 *
 * EnableHystrixDashboard注解 - 开启HystrixDashboard提供的可视化界面。
 */
@SpringBootApplication
@EnableCircuitBreaker
@EnableHystrixDashboard
@EnableFeignClients(basePackages = {"com.bjsxt.feign.client.service"})
public class FeignClientApp {
    public static void main(String[] args) {
        SpringApplication.run(FeignClientApp.class, args);
    }
}

4 访问Hystrix监控数据结果

通过浏览器访问提供监控访问路径的应用,具体地址为:
http://ip:port/actuator/hystrix.stream

得到的监控结果如下:
在这里插入图片描述

这种监控数据的获取都是JSON数据。且数据量级较大。不易于查看。可以使用Hystrix Dashboard提供的视图界面来观察监控结果。视图界面访问路径为: http://ip:port/hystrix。

在这里插入图片描述

进入后的监控视图界面具体含义如下:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AloneDrifters

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值