互联网架构服务降级熔断Hystrix学习

熔断,熔断服务,为了防止整个系统故障,包含子和下游服务。

降级,抛弃一些非核心的接口和数据。

熔断和降级相互交集

相同点:

1)从可用性和可靠性出发,为了防止系统崩溃。

2)最终让用户体会到的事某些功能暂时不能用

不同点:

1)服务熔断一般是下游服务故障导致的,而服务降级一般是从整体负荷考虑,由调用方控制。

Hystrix

提供了熔断、隔离、fallback、cache、监控等功能。

实践实例

1 加入依赖

http://cloud.spring.io/spring-cloud-netflix/single/spring-cloud-netflix.html#_circuit_breaker_hystrix_clients

how to include Hystrix


去阿里用仓库下载,修改maven仓库地址
pom.xml中修改 

<repositories>
<repository>
<id>nexus-aliyun</id>
<name>Nexus aliyun</name>
<layout>default</layout>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>

2 增加注解
启动类里面增加注解
@EnableCircuitBreaker

注解越来越多-> SpringCloudApplication注解

3、API接口编码实战
熔断-》降级

1)最外层api使用,好比异常处理(网络异常,参数或者内部调用问题)
api方法上增加 @HystrixCommand(fallbackMethod = "saveOrderFail")

编写fallback方法实现,方法签名一定要和api方法签名一致(注意点!!!)

 feign结合hystrix断路器开发

1)开启feign支持hystrix (注意,一定要开启,旧版本默认支持,新版本默认关闭)
feign:
hystrix:
enabled: true

2)FeignClient(name="xxx", fallback=xxx.class ), class需要继承当前FeignClient的类

下单接口

 

获取商品异常

 

熔断降级服务异常报警通知实战
简介:完善服务熔断处理,报警机制完善

1、加入redis依赖

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

2、配置redis链接信息

redis:
database: 0
host: 127.0.0.1
port: 6379
timeout: 2000

3、使用

//监控报警
String saveOrderKye = "save-order";
String sendValue = redisTemplate.opsForValue().get(saveOrderKye);
final String ip = request.getRemoteAddr();
new Thread( ()->{
if (StringUtils.isBlank(sendValue)) {
System.out.println("紧急短信,用户下单失败,请离开查找原因,ip地址是="+ip);
//发送一个http请求,调用短信服务 TODO
redisTemplate.opsForValue().set(saveOrderKye, "save-order-fail", 20, TimeUnit.SECONDS);
}else{
System.out.println("已经发送过短信,20秒内不重复发送");
}
}).start();

断路器Dashboard监控仪表盘实战

1、加入依赖

<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>

2、启动类增加注解
@EnableHystrixDashboard


3、配置文件增加endpoint

management:
endpoints:
web:
exposure:
include: "*"

4、访问入口
http://localhost:8781/hystrix

Hystrix Dashboard输入: http://localhost:8781/actuator/hystrix.stream


参考资料
默认开启监控配置
https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-security-actuator

配置文件类:
spring-configuration-metadata.json


猜你喜欢

转载自www.cnblogs.com/dingpeng9055/p/12411179.html