实战目标
1 搭建实战Demo,集成SpringCloud Gateway网关,Nacos注册中心,Hystrix熔断器
2 实现测试目标: 通过Gateway网关访问目标服务api 如: /provider-test/discovery/one 当访问超时时间达到3000ms时,Hystrix熔断工作,实现友好提示:当前服务器繁忙,请稍后重试
复制代码
搭建过程
1 核心Hystrix Maven 引入
复制代码
<!--熔断器 hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
复制代码
2 核心yml配置
复制代码
spring:
application:
name: gateway-main
#配置nacos注册中心
cloud:
nacos:
## 注册中心配置
discovery:
# nacos的服务地址,nacos-server中IP地址:端口号
server-addr: 121.199.72.238:8848
# 熔断器Hystrix
gateway:
routes:
- id: provider-test-one
uri: lb://nacos-main
predicates:
- Path=/provider-test/**
# Hystrix相关
filters:
- name: Hystrix
args:
name: fallbackcmd
# 请求超时时,将会进行转发到 /fallback
fallbackUri: forward:/provider-test/fallback
# Hystrix 配置
hystrix:
command:
fallbackcmd:
execution:
isolation:
thread:
timeoutInMilliseconds: 3000 #服务超时时间
复制代码
3 对应Controller实现
步骤2配置了当/provider-test/** 服务请求超过3000ms时,会跳转到路径/provider-test/fallback 上进行友好服务繁忙提示,这里写一个简单demo controller即可
复制代码
Hystrix 熔断器测试
测试目标是 访问如:/provider-test/discovery/one 当访问超时时间达到3000ms时,Hystrix熔断工作,实现友好提示:当前服务器繁忙,请稍后重试
内部通过线程休眠模拟访问时间
// Hystrix测试,模拟并发访问,接口不同执行时间
Thread.sleep((int) (Math.random() * 10000));
复制代码
通过Postman向网关发送api访问请求:http://localhost:9999/provider-test/discovery/one
网关会在Nacos注册中心找到对应的服务提供商地址,然后进行api访问
1 当api访问超时超过3000ms时,被Hystrix处理,跳转到目标处理api/provider-test/fallback,如图
复制代码
2 api未超时,访问正常
复制代码
实战源码Demo下载
SpringCloud Gateway+Nacos+Hystrix整合服务超时实战Demo 源码)
TODO
Hystrix源码分析,如何控制超时熔断,底层源码机制鉴赏解析
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END