微服务 springcloud 05 hystrix框架,降级,可视化Hystrix dashboard 仪表盘,熔断

news2025/2/1 20:39:18

01.微服务宕机时,ribbon 无法转发请求
关闭 user-service 和 order-service
在这里插入图片描述
在这里插入图片描述
02.hystrix框架
在这里插入图片描述
在这里插入图片描述
03.创建hystrix项目,hystrix与ribbon经常一起出现
第一步:复制 sp06-ribbon 项目,命名为sp07-hystrix
选择 sp06-ribbon 项目,ctrl-c,ctrl-v,复制为sp07-hystrix
关闭 sp06-ribbon 项目,后续测试使用 sp07-hystrix 项目(其中已经写好了ribbon)

第二步:修改 pom.xml
01.修改pom的项目名
在这里插入图片描述
02.添加 hystrix 起步依赖

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

第三步:修改 application.yml
在这里插入图片描述
修改项目的名称

spring:
  application:
    name: hystrix

server:
  port: 3001
  
eureka:
  client:
    service-url:
      defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
ribbon:
  MaxAutoRetriesNextServer: 2
  MaxAutoRetries: 1
  OkToRetryOnAllOperations: true

第四步:修改主启动类,添加@EnableCircuitBreaker 启用 hystrix 断路器
启动断路器,断路器提供两个核心功能:
降级:超时、出错、不可到达时,对服务降级,返回错误信息或者是缓存数据
熔断:当服务压力过大,错误比例过多时,熔断所有请求,所有请求直接降级

package cn.tedu.sp07;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

//@EnableCircuitBreaker
//@EnableDiscoveryClient
//@SpringBootApplication

@SpringCloudApplication
public class Sp07HystrixApplication {

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

	//创建RestTemplate实例,并存入spring容器中
	@LoadBalanced //负载均衡注解
	@Bean
	public RestTemplate getRestTemplate() {
		SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory();
		f.setConnectTimeout(1000);
		f.setReadTimeout(1000);
		return new RestTemplate(f);
		//return new RestTemplate();
	}
}

也可以使用@SpringCloudApplication,@SpringCloudApplication=@EnableCircuitBreaker+@EnableDiscoveryClient+@SpringBootApplication

第五步:RibbonController 中添加降级方法
为每个方法添加降级方法,例如 getItems() 添加降级方法 getItemsFB()
添加 @HystrixCommand 注解,指定降级方法名

package cn.tedu.sp07.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.pojo.Order;
import cn.tedu.sp01.pojo.User;
import cn.tedu.web.util.JsonResult;

@RestController
public class RibbonController {
	@Autowired
	private RestTemplate rt;

	@GetMapping("/item-service/{orderId}")
	@HystrixCommand(fallbackMethod = "getItemsFB") //指定降级方法的方法名
	public JsonResult<List<Item>> getItems(@PathVariable String orderId) {
		//向指定微服务地址发送 get 请求,并获得该服务的返回结果 
		//{1} 占位符,用 orderId 填充
		return rt.getForObject("http://item-service/{1}", JsonResult.class, orderId);
	}

	@PostMapping("/item-service/decreaseNumber")
	@HystrixCommand(fallbackMethod = "decreaseNumberFB")
	public JsonResult decreaseNumber(@RequestBody List<Item> items) {
		//发送 post 请求
		return rt.postForObject("http://item-service/decreaseNumber", items, JsonResult.class);
	}


	@GetMapping("/user-service/{userId}")
	@HystrixCommand(fallbackMethod = "getUserFB")
	public JsonResult<User> getUser(@PathVariable Integer userId) {
		return rt.getForObject("http://user-service/{1}", JsonResult.class, userId);
	}

	@GetMapping("/user-service/{userId}/score") 
	@HystrixCommand(fallbackMethod = "addScoreFB")
	public JsonResult addScore(
			@PathVariable Integer userId, Integer score) {
		return rt.getForObject("http://user-service/{1}/score?score={2}", JsonResult.class, userId, score);
	}


	@GetMapping("/order-service/{orderId}")
	@HystrixCommand(fallbackMethod = "getOrderFB")
	public JsonResult<Order> getOrder(@PathVariable String orderId) {
		return rt.getForObject("http://order-service/{1}", JsonResult.class, orderId);
	}

	@GetMapping("/order-service")
	@HystrixCommand(fallbackMethod = "addOrderFB")
	public JsonResult addOrder() {
		return rt.getForObject("http://order-service/", JsonResult.class);
	}
	
	//降级方法的参数和返回值,需要和原始方法一致,方法名任意
		public JsonResult<List<Item>> getItemsFB(String orderId) {
			return JsonResult.err("获取订单商品列表失败");
		}
		public JsonResult decreaseNumberFB(List<Item> items) {
			return JsonResult.err("更新商品库存失败");
		}
		public JsonResult<User> getUserFB(Integer userId) {
			return JsonResult.err("获取用户信息失败");
		}
		public JsonResult addScoreFB(Integer userId, Integer score) {
			return JsonResult.err("增加用户积分失败");
		}
		public JsonResult<Order> getOrderFB(String orderId) {
			return JsonResult.err("获取订单失败");
		}
		public JsonResult addOrderFB() {
			return JsonResult.err("添加订单失败");
		}
}

第六步:hystrix 超时设置
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
hystrix等待超时后, 会执行降级代码, 快速向客户端返回降级结果, 默认超时时间是1000毫秒,为了测试 hystrix 降级,我们把 hystrix 等待超时设置得非常小(500毫秒)
此设置一般应大于 ribbon 的重试超时时长,例如 10 秒
在application.yml文件中:

spring:
  application:
    name: hystrix

server:
  port: 3001
  
eureka:
  client:
    service-url:
      defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
ribbon:
  MaxAutoRetriesNextServer: 2
  MaxAutoRetries: 1
  OkToRetryOnAllOperations: true

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

第七步:启动项目进行测试
在这里插入图片描述
通过 hystrix 服务,访问可能超时失败的 item-service
http://localhost:3001/item-service/35

通过 hystrix 服务,访问未启动的 user-service
http://localhost:3001/user-service/7

可以看到,如果 item-service 请求超时,hystrix 会立即执行降级方法
访问 user-service,由于该服务未启动,hystrix也会立即执行降级方法
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
第五步到第七步是hystrix的降级处理
hystrix 对请求的降级和熔断,可以产生监控信息,hystrix dashboard可以实时的进行监控
监控项目的数据进行可视化,Hystrix dashboard 仪表盘

在这里插入图片描述

第八步:sp07-hystrix 项目添加 actuator,并暴露 hystrix 监控端点
actuator 是 spring boot 提供的服务监控工具,提供了各种监控信息的监控端点
management.endpoints.web.exposure.include 配置选项,
可以指定端点名,来暴露监控端点
如果要暴露所有端点,可以用 “*”
在这里插入图片描述
第九步:pom.xml 添加 actuator 依赖
右键点击项目或pom.xml, 编辑起步依赖, 添加 actuator 依赖

在这里插入代码片在这里插入图片描述
第十步:调整 application.yml 配置,并暴露 hystrix.stream 监控端点

spring:
  application:
    name: hystrix

server:
  port: 3001
  
eureka:
  client:
    service-url:
      defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
ribbon:
  MaxAutoRetriesNextServer: 2
  MaxAutoRetries: 1
  OkToRetryOnAllOperations: true

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 10000
management:
  endpoints:
    web:
      exposure:
        include: hystrix.stream

第十一步:访问 actuator 路径,查看监控端点
http://localhost:3001/actuator
在这里插入图片描述
第十二步:新建 sp08-hystrix-dashboard 项目
在这里插入图片描述
在这里插入图片描述
结果的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>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.1.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>cn.tedu</groupId>
	<artifactId>sp08-hystrix-dashboard</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>sp08-hystrix-dashboard</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
		<spring-cloud.version>Hoxton.SR12</spring-cloud.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</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>
	</dependencies>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>${spring-cloud.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

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

</project>

第十三步:修改sp08-hystrix-dashboard项目的application.yml

spring:
  application:
    name: hystrix-dashboard
    
server:
  port: 4001
  
eureka:
  client:
    service-url:
      defaultZone: http://eureka1:2001/eureka,http://eureka2:2002/eureka

hystrix:
  dashboard:
    proxy-stream-allow-list: localhost

第十四步:主程序添加 @EnableHystrixDashboard 和 @EnableDiscoveryClient

package cn.tedu.sp08;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;

@EnableDiscoveryClient
@EnableHystrixDashboard
@SpringBootApplication
public class Sp08HystrixDashboardApplication {

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

}

第十五步:启动,并访问测试
在这里插入图片描述
访问 hystrix dashboard
http://localhost:4001/hystrix
在这里插入图片描述
填入 hystrix 的监控端点,开启监控
在这里插入图片描述
通过 hystrix 访问服务多次,观察监控信息
http://localhost:3001/item-service/35

http://localhost:3001/user-service/7
http://localhost:3001/user-service/7/score?score=100

http://localhost:3001/order-service/123abc
http://localhost:3001/order-service/
在这里插入图片描述
在这里插入图片描述
hystrix 熔断
整个链路达到一定的阈值,默认情况下,10秒内产生超过20次请求,则符合第一个条件。
满足第一个条件的情况下,如果请求的错误百分比大于阈值,则会打开断路器,默认为50%。
Hystrix的逻辑,先判断是否满足第一个条件,再判断第二个条件,如果两个条件都满足,则会开启断路器

断路器打开 5 秒后,会处于半开状态,会尝试转发请求,如果仍然失败,保持打开状态,如果成功,则关闭断路器
第十六步:
使用 apache 的并发访问测试工具 ab
http://httpd.apache.org/docs/current/platform/windows.html#down
在这里插入图片描述
用 ab 工具,以并发50次,来发送20000个请求
ab -n 20000 -c 50 http://localhost:3001/item-service/35
断路器状态为 Open,所有请求会被短路,直接降级执行 fallback 方法
在这里插入图片描述
hystrix 配置

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
请求超时时间,超时后触发失败降级

hystrix.command.default.circuitBreaker.requestVolumeThreshold
10秒内请求数量,默认20,如果没有达到该数量,即使请求全部失败,也不会触发断路器打开

hystrix.command.default.circuitBreaker.errorThresholdPercentage
失败请求百分比,达到该比例则触发断路器打开

hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds
断路器打开多长时间后,再次允许尝试访问(半开),仍失败则继续保持打开状态,如成功访问则关闭断路器,默认 5000

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/648712.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

一个Java程序员的C++学习之路

最近接到了一个Windows客户端开发&#xff0c;需要用到C&#xff0c;由于大学嵌入式学习的时候用到了这种东西&#xff0c;虽然没忘记吧&#xff0c;但是还是打算用一周的时间复习一下&#xff0c;下面是我的复习笔记&#xff0c;当然了&#xff0c;也是基于尚硅谷和黑马的笔记…

NLP——Ethics伦理

文章目录 Core NLP ethics conceptsbiasprivacy Group discussionAutomatic Prison Term PredictionAutomatic CV ProcessingLanguage Community Classification Core NLP ethics concepts 自然语言处理&#xff08;NLP&#xff09;的伦理问题是一个日益重要的领域&#xff0c…

007、体系架构之PD

PD PD架构主要功能路由功能 TSO分配TSO概念分配过程时间窗口同步过程 调度总流程信息收集调度的实现调度需求生成调度执行调度调度的基本操作调度的策略 lablelabel与高可用label的配置 PD架构 PD&#xff1a;有高可用和强一致性。 也有leader。使用奇数的节点数量。它需要存储…

10 分钟理解微服务、容器和 Kubernetes及其关系

什么是微服务&#xff1f; 什么是微服务&#xff1f;你应该使用微服务吗&#xff1f;微服务与容器和 Kubernetes 有什么关系&#xff1f;如果这些事情在您的日常生活中不断出现&#xff0c;并且您需要在 10 分钟内进行概述&#xff0c;那么这篇博文适合您。 从根本上讲&#x…

小红书企业号限流原因有哪些,限流因素

作为企业、品牌在小红书都有官方账号&#xff0c;很多人将注册小红书企业号看作是获取品牌宣推“特权”的必行之举。事实真的如此吗&#xff0c;那为什么小红书企业号限流频发&#xff0c;小红书企业号限流原因有哪些&#xff0c;限流因素。 一、小红书企业号限流真的存在吗 首…

SpringBoot中Redis的基础使用

基础使用 首先引入依赖 <!-- redis依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>redis.clients</g…

中断处理流程以及程序状态寄存器CPSR的本质

文章目录 前言一、当前程序状态寄存器&#xff08;CPSR&#xff09;二、异常的分类2.1 7个异常源2.2 异常的优先级2.3 为什么FIQ比IRQ快&#xff1f;2.4 异常与工作模式的区别 三、异常的处理流程3.1 异常处理机制3.2 进入异常处理流程&#xff1a;3.3 退出异常的处理流程&…

送给蓝初小萌新系列(1)——Linux入侵排查

一、linux系统资源 1、linux被入侵的症状 linux系统资源用户和日志文件和命令篡改启动项和定时任务挖矿脚本分析 2、linux系统资源 2.1、CPU内存磁盘 top -c -o %CPU:查看cpu占用情况&#xff08;按cpu排序&#xff09; top -c -o %MEM:查看内存占用情况&#xff08;按内存…

兼容性测试如何提高网站的可用性?

兼容性测试如何提高网站的可用性? 在现代社会&#xff0c;网站已经成为了人们获取信息、进行交流的主要渠道之一。但是&#xff0c;在网站的设计和开发中&#xff0c;往往会存在兼容性问题&#xff0c;导致不同浏览器或设备的用户无法顺利地访问和使用网站&#xff0c;降低了网…

华为OD机试之最长连续子序列(Java源码)

最长连续子序列 题目描述 有N个正整数组成的一个序列。给定整数sum&#xff0c;求长度最长的连续子序列&#xff0c;使他们的和等于sum&#xff0c;返回此子序列的长度&#xff0c; 如果没有满足要求的序列&#xff0c;返回-1。 输入描述 第一行输入是&#xff1a;N个正整数…

【Spring 核心 | IoC】

IoC IoC 简介定义&#xff1a;IoC 和 DIBeanIoC 容器Ioc IoC容器 IoC 简介 定义&#xff1a; IoC即控制反转&#xff08;Inversion of Control&#xff0c;缩写为 IoC&#xff09;。IoC又称为依赖倒置原则&#xff08;设计模式六大原则之一&#xff09;。 IoC意味着将你设计好…

走近mysql运算符|靠它就够啦

这里写目录标题 比较运算符的使用等号运算符<>安全等于不等于运算符<>/!非符号类型的运算符BETWEEN ANDINLIKEPEGEXP/ RLIKE 逻辑运算符使用位运算符 比较运算符的使用 等号运算符 判断等号两边的值&#xff0c;字符串或表达式是否相等&#xff0c;如果相等则返回…

Hadoop/Hive/Spark小文件处理

什么是小文件&#xff1f; 小文件指的是文件size比HDFS的block size小很多的文件。Hadoop适合处理少量的大文件&#xff0c;而不是大量的小文件。 hadoop小文件常规的处理方式 1、小文件导致的问题 首先&#xff0c;在HDFS中&#xff0c;任何block&#xff0c;文件或者目录…

吴恩达471机器学习入门课程1第1周——梯度下降

文章目录 1加载数据集2计算COST(均值平方差&#xff0c;1/2m(y_pre - y))3计算梯度4画出成本曲线5梯度下降 import math, copy import numpy as np import matplotlib.pyplot as plt plt.style.use(./deeplearning.mplstyle) from lab_utils_uni import plt_house_x, plt_conto…

华为OD机试真题 JavaScript 实现【找出通过车辆最多颜色】【2023Q1 100分】

一、题目描述 在一个狭小的路口&#xff0c;每秒只能通过一辆车&#xff0c;假如车辆的颜色只有3种&#xff0c;找出n秒内经过的最多颜色的车辆数量。 三种颜色编号为0、1、2。 二、输入描述 第一行输入的是通过的车辆颜色信息 [0 1 1 2] 代表4秒钟通过的车辆颜色分别是0 1…

手把手教你使用CONN(预处理)

CONN软件介绍 &#xff08;1&#xff09;CONN是一个基于Matlab的跨平台软件&#xff0c;用于计算、显示和分析功能磁共振成像&#xff08;fcMRI&#xff09;中的功能连通性。也可用于静息状态数据&#xff08;rsfMRI&#xff09;以及任务相关设计。 &#xff08;2&#xff09…

Vue的组合式

1. 概念 选项式API&#xff1a;将相同类型的代码放在一起&#xff08;比如所有数据、所有用到的方法等等&#xff09;当代码业务板块过多时&#xff0c;不方便写代码和后期维护 组合式API&#xff1a;将同一业务的相关代码放在一起&#xff08;比如说数据&#xff0c;方法&am…

什么是同源策略

文章目录 同源策略同源策略的目的同源策略分类 同源策略 同源策略是指浏览器的一种安全机制&#xff0c;用于限制来自不同源&#xff08;即域、协议或端口&#xff09;的文档或脚本之间的交互操作。 根据同源策略&#xff0c;浏览器只允许当前网页与同一源下的其他资源进行交…

Linux之CentOS 7.9部署Oracle 11g r2 静默安装实测验证(无桌面模式)

前言&#xff1a;因前段时间一直部署的windows环境的oracle&#xff0c;这次记录下linux下的部署方式&#xff0c;当然还有更多的其他部署&#xff0c;大家可根据自身环境及学习来了解。一般静默安装主要还是要提前准备源包&#xff0c;还有很多依赖包&#xff0c;另外就是配置…

如何显示文件后缀名,这4个方法很简单!

Anna最近想对电脑里的文件进行分类&#xff0c;但有些未知类型的文件&#xff0c;她想查看文件的类型并进行分类&#xff0c;可是她不知道如何显示文件后缀名&#xff0c;因此向大家求助。 在计算机操作中&#xff0c;文件的后缀名是文件名的一部分&#xff0c;用于标识文件的类…