熔断 为了防止整个系统故障,包含子和下游服务(订单创建 这个服务暂时关闭,请求其他服务器中订单创建)
降级 抛弃一些非核心的接口( 可能这个接口的服务器已经被关闭了),依旧能执行
相同点: 从可用性和可靠性处罚,为了防止系统崩溃
最终让用户体验到的是某些功能暂时不能用
不同点:服务熔断一般是下游服务故障导致的,而服务降级一般是从整体系统负荷考虑,由调用方控制
Feign结合Hystrix
#修改调用超时时间
feign:
client:
config:
default:
connectTimeout: 2000
readTimeout: 2000 //超时时间
hystrix:
enabled: true
项目的启动类上需要加注解 @EnableCircuitBreaker
控制层中方法上添加注解
@HystrixCommand(fallbackMethod = "createOrderFail") //熔断处理
@RequestMapping(value = "/create", method = RequestMethod.POST)
public ReturnMsg createOrder(@RequestBody OrderDTO orderDTO, HttpServletRequest request){
productService.findById(3);
return ReturnMsg.success();
}
方法中的参数一定要与上一一对应
private ReturnMsg createOrderFail(@RequestBody OrderDTO orderDTO, HttpServletRequest request) {
String saveOrderKys = "createOrder";
final String ip = request.getRemoteAddr();
final int post = request.getLocalPort();
String xx = "用户下单失败, 请查找原因!ip:: " + ip + ": " + post +"method :"+ saveOrderKys;
System.out.println("紧急短信, 用户下单失败, 请查找原因!ip:: " + ip + ": " + post);
return ReturnMsg.fail().add("data","请求失败,请重新尝试!: "+xx);
}
服务层做降级
Service层 调用产品服务
@FeignClient(name = "product-service", contextId = "productClient", fallback = ProductClientFallback.class)
public interface ProductClient {
@RequestMapping("api/v1/product/find/{id}")
String findById(@PathVariable("id") Integer id);
}
/**
* 针对商品服务, 做降级处理
*/
@Component
public class ProductClientFallback implements ProductClient {
@Override
public String findById(Integer id) {
System.out.println("查询产品 " + id + " 失败");
System.out.println("降级处理");
System.out.println("feign 调用 product-service 异常");
return null;
}
}
‘product-service’ 服务中的接口
@RequestMapping(value = "api/v1/product/find/{id}", method = RequestMethod.POST)
public ReturnMsg find(@PathVariable(value = "id") Integer id){
sleep(3000); //已经超过上面 Hystrix.readTimeout 所定义的超时时间
return ReturnMsg.success();
}
#暴露全部的监控信息
断路Dashboard监控器仪表盘实战
项目的启动类上需要加注解 @EnableHystrixDashboard
#暴露全部的监控信息
management:
endpoints:
web:
exposure:
include: "*"
#可能也需要下面的配置
hystrix:
dashboard:
proxyStreamAllowList: "localhost"
访问路径
http://localhost:8881/hystrix
填写路径
http://localhost:8881/actuator/hystrix.stream
pom.xml
<!--hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!--断路器Dashboard基础使用和查看-->
<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-actuator</artifactId>
</dependency>