Spring Cloud Hystrix 详细示-元一软件
Hystrix 是 Spring Cloud 中实现服务熔断、降级、隔离的核心组件用于解决微服务架构中的雪崩效应核心是快速失败、优雅降级、自动恢复。以下从环境搭建、基础使用、高级配置、Feign 整合、监控5 个维度提供完整示例。一、项目环境准备1. 依赖引入Maven创建 Spring Boot 项目添加 Hystrix 及 Spring Cloud 基础依赖xmlparent groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-parent/artifactId version2.3.12.RELEASE/version !-- 适配 Spring Cloud Hoxton.SR12 -- /parent dependencies !-- Spring Boot Web -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-web/artifactId /dependency !-- Spring Cloud Netflix Hystrix 核心依赖 -- dependency groupIdorg.springframework.cloud/groupId artifactIdspring-cloud-starter-netflix-hystrix/artifactId /dependency !-- 服务注册与发现Eureka可选用于服务调用 -- dependency groupIdorg.springframework.cloud/groupId artifactIdspring-cloud-starter-netflix-eureka-client/artifactId /dependency !-- 负载均衡RestTemplate 调用 -- dependency groupIdorg.springframework.cloud/groupId artifactIdspring-cloud-starter-loadbalancer/artifactId /dependency /dependencies dependencyManagement dependencies dependency groupIdorg.springframework.cloud/groupId artifactIdspring-cloud-dependencies/artifactId versionHoxton.SR12/version typepom/type scopeimport/scope /dependency /dependencies /dependencyManagement2. 启动类开启 Hystrix在启动类添加EnableHystrix或EnableCircuitBreaker注解开启熔断功能java运行import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.netflix.hystrix.EnableHystrix; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; SpringBootApplication EnableHystrix // 开启 Hystrix 熔断、降级功能 public class HystrixDemoApplication { public static void main(String[] args) { SpringApplication.run(HystrixDemoApplication.class, args); } // 注册负载均衡的 RestTemplate用于调用远程服务 Bean LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } }3. 基础配置application.ymlyamlserver: port: 8080 # 服务端口 spring: application: name: hystrix-demo # 服务名 eureka: client: service-url: defaultZone: http://localhost:8761/eureka/ # Eureka 注册中心地址可选二、基础使用HystrixCommand 实现熔断降级1. 核心注解HystrixCommand该注解用于标记需要 Hystrix 保护的方法核心参数fallbackMethod指定降级方法服务失败 / 超时时执行commandProperties配置熔断、超时、隔离等规则groupKey命令分组用于线程池隔离threadPoolKey线程池标识实现线程池隔离2. 示例 1基础熔断降级RestTemplate 调用创建服务类模拟调用远程用户服务配置熔断规则与降级逻辑java运行import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; Service public class UserService { Autowired private RestTemplate restTemplate; /** * 调用远程用户服务配置熔断与降级 * 熔断规则10秒内请求数≥20失败率≥50%则熔断5秒 * 超时时间3秒 */ HystrixCommand( fallbackMethod getUserFallback, // 降级方法 commandProperties { // 熔断触发条件请求数阈值 HystrixProperty(name circuitBreaker.requestVolumeThreshold, value 20), // 熔断触发条件失败率阈值百分比 HystrixProperty(name circuitBreaker.errorThresholdPercentage, value 50), // 熔断后休眠时间毫秒休眠后进入半开状态 HystrixProperty(name circuitBreaker.sleepWindowInMilliseconds, value 5000), // 执行超时时间毫秒 HystrixProperty(name execution.isolation.thread.timeoutInMilliseconds, value 3000) } ) public String getUserById(Long userId) { // 调用远程用户服务user-service 为注册中心的服务名 return restTemplate.getForObject(http://user-service/users/ userId, String.class); } /** * 降级方法参数、返回值必须与原方法一致 * 可接收 Throwable 参数获取异常信息 */ public String getUserFallback(Long userId, Throwable throwable) { return 用户服务不可用降级返回用户ID userId 异常信息 throwable.getMessage(); } }3. 示例 2多级降级级联 Fallback当一级降级也可能失败时配置多级降级java运行Service public class OrderService { HystrixCommand(fallbackMethod orderFallback1) public String createOrder(Long userId, Long productId) { // 模拟创建订单可能失败 if (Math.random() 0.3) { throw new RuntimeException(订单服务异常); } return 订单创建成功用户 userId 商品 productId; } // 一级降级 public String orderFallback1(Long userId, Long productId, Throwable e) { System.out.println(一级降级执行 e.getMessage()); // 模拟一级降级失败 if (Math.random() 0.5) { throw new RuntimeException(一级降级失败); } return 一级降级订单创建失败稍后重试; } // 二级降级一级降级失败时执行 HystrixCommand(fallbackMethod orderFallback2) public String orderFallback1(Long userId, Long productId) { return 二级降级系统繁忙请稍后再试; } // 最终降级 public String orderFallback2(Long userId, Long productId) { return 最终降级服务不可用请联系客服; } }4. 示例 3根据异常类型定制降级在降级方法中通过Throwable判断异常类型返回不同降级信息java运行Service public class PayService { HystrixCommand(fallbackMethod payFallback) public String pay(Long orderId, Double amount) { // 模拟不同异常 if (Math.random() 0.7) { throw new RuntimeException(支付服务内部错误); } else if (Math.random() 0.4) { throw new java.util.concurrent.TimeoutException(支付服务超时); } return 支付成功订单 orderId 金额 amount; } public String payFallback(Long orderId, Double amount, Throwable e) { if (e instanceof java.util.concurrent.TimeoutException) { return 降级支付服务超时请稍后重试; } else if (e instanceof RuntimeException) { return 降级支付服务异常订单 orderId 支付失败; } else { return 降级系统繁忙请稍后再试; } } }三、高级配置线程池隔离与全局配置1. 线程池隔离核心Hystrix 默认使用线程池隔离为每个服务调用分配独立线程池避免一个服务故障耗尽所有线程。java运行Service public class StockService { /** * 配置独立线程池核心线程数5最大线程数10队列大小20 */ HystrixCommand( fallbackMethod stockFallback, threadPoolKey stockThreadPool, // 线程池标识 threadPoolProperties { HystrixProperty(name coreSize, value 5), // 核心线程数 HystrixProperty(name maximumSize, value 10), // 最大线程数 HystrixProperty(name maxQueueSize, value 20) // 队列大小 } ) public String deductStock(Long productId, Integer num) { return restTemplate.getForObject(http://stock-service/stock/deduct?productId productId num num, String.class); } public String stockFallback(Long productId, Integer num) { return 库存服务降级商品 productId 库存扣减失败; } }2. 全局配置application.yml通过配置文件统一设置 Hystrix 全局规则避免每个方法重复配置yamlhystrix: command: default: # 全局默认配置 circuitBreaker: requestVolumeThreshold: 20 # 10秒内请求数≥20才判断熔断 errorThresholdPercentage: 50 # 失败率≥50%触发熔断 sleepWindowInMilliseconds: 5000 # 熔断后休眠5秒 execution: isolation: thread: timeoutInMilliseconds: 3000 # 全局超时3秒 fallback: isolation: semaphore: maxConcurrentRequests: 10 # 降级方法最大并发数 threadpool: default: # 全局线程池配置 coreSize: 10 # 核心线程数 maximumSize: 20 # 最大线程数 maxQueueSize: 50 # 队列大小四、Feign 整合 Hystrix微服务常用Spring Cloud Feign 天然支持 Hystrix无需额外注解只需开启配置并实现降级接口。1. 开启 Feign Hystrixapplication.ymlyamlfeign: hystrix: enabled: true # 开启 Feign 整合 Hystrix2. Feign 接口定义java运行import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; // 指定服务名与降级类 FeignClient(value user-service, fallback UserFeignFallback.class) public interface UserFeignClient { GetMapping(/users/{userId}) String getUserById(PathVariable(userId) Long userId); }3. 降级类实现java运行import org.springframework.stereotype.Component; Component public class UserFeignFallback implements UserFeignClient { Override public String getUserById(Long userId) { return Feign 降级用户服务不可用用户ID userId; } }4. 使用 Feign 调用java运行Service public class FeignUserService { Autowired private UserFeignClient userFeignClient; public String getUser(Long userId) { return userFeignClient.getUserById(userId); } }五、Hystrix 监控Dashboard1. 引入监控依赖xmldependency groupIdorg.springframework.cloud/groupId artifactIdspring-cloud-starter-netflix-hystrix-dashboard/artifactId /dependency dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-actuator/artifactId /dependency2. 开启监控启动类java运行import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; SpringBootApplication EnableHystrix EnableHystrixDashboard // 开启 Hystrix 监控仪表盘 public class HystrixDemoApplication { // ... 其他代码 }3. 暴露监控端点application.ymlyamlmanagement: endpoints: web: exposure: include: hystrix.stream # 暴露 Hystrix 监控流4. 访问监控面板启动服务访问http://localhost:8080/hystrix在输入框填入监控流地址http://localhost:8080/actuator/hystrix.stream点击「Monitor Stream」即可查看服务调用的熔断状态、请求数、失败率、线程池状态等实时数据。六、核心原理总结断路器状态Closed闭合正常调用统计失败率Open打开触发熔断直接执行降级不调用远程服务Half-Open半开熔断休眠后允许少量请求测试服务是否恢复成功则闭合失败则重新打开隔离机制线程池隔离默认/ 信号量隔离避免服务间相互影响降级逻辑服务失败 / 超时 / 熔断时快速返回预设响应提升用户体验
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2460061.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!