# 0.服务熔断的实现思路 - 引入hystrix依赖,并开启熔断器(断路器) - 模拟降级方法 - 进行调用测试
# 1.项目中引入hystrix依赖
org.springframework.cloud
spring-cloud-starter-netflix-hystrix
# 2.开启断路器
@SpringBootApplication @EnableCircuitBreaker //用来开启断路器 public class Products9998Application { public static void main(String[] args) { SpringApplication.run(Products9998Application.class, args); } }
# 3.使用HystrixCommand注解实现断路
//服务熔断 @GetMapping("/product/break") @HystrixCommand(fallbackMethod = "testBreakFall" ) public String testBreak(int id){ log.info("接收的商品id为: "+ id); if(id<=0){ throw new RuntimeException("数据不合法!!!"); } return "当前接收商品id: "+id; } public String testBreakFall(int id){ return "当前数据不合法: "+id; }
# 4.访问测试 - 正常参数访问 - 错误参数访问
A service failure in the lower level of services can cause cascading failure all the way up to the user. When calls to a particular service exceed circuitBreaker.requestVolumeThreshold (default: 20 requests) and the failure percentage is greater than circuitBreaker.errorThresholdPercentage (default: >50%) in a rolling window defined by metrics.rollingStats.timeInMilliseconds (default: 10 seconds), the circuit opens and the call is not made. In cases of error and an open circuit, a fallback can be provided by the developer. --摘自官方
# 面试重点问题: 断路器流程

@GetMapping("/product/hystrix") @HystrixCommand(fallbackMethod = "testHystrixFallBack") //通过HystrixCommand降级处理 指定出错的方法 public String testHystrix(String name) { log.info("接收名称为: " + name); int n = 1/0; return "服务[" + port + "]响应成功,当前接收名称为:" + name; } //服务降级处理 public String testHystrixFallBack(String name) { return port + "当前服务已经被降级处理!!!,接收名称为: "+name; }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/176168.html原文链接:https://javaforall.net
