#### 微服务熔断/降级/限流——全局配置 jeecg-cloud-gateway 模块中application.yml加入如下配置 ~~~ # 全局熔断降级配置 default-filters: - name: Hystrix args: name: default #转发地址 fallbackUri: 'forward:/fallback' - name: Retry args: #重试次数,默认值是 3 次(负载均衡客户端发现远程请求实例不可到达后,去重试其他实例) retries: 3 #HTTP 的状态返回码 statuses: BAD_GATEWAY,BAD_REQUEST #指定哪些方法的请求需要进行重试逻辑,默认值是 GET 方法 methods: GET,POST # hystrix 信号量隔离,60秒后自动超时(生成环境根据各自项目情况调整,如需测试请将时间调小点) hystrix: enabled: true command: default: execution: isolation: strategy: SEMAPHORE thread: #超时时间 timeoutInMilliseconds: 60000 ~~~ 熔断处理器编写 ~~~ /** * 响应超时熔断处理器 * * @author zyf */ @RestController public class FallbackController { /** * 全局熔断处理 * @return */ @RequestMapping("/fallback") public Mono<String> fallback() { return Mono.just("访问超时,请稍后再试!"); } } ~~~ #### 熔断路由配置 nacos中json配置,xml配置参考全局配置写法 ``` [ { "id": "jeecg-cloud-demo", "order": 1, "predicates": [ { "name": "Path", "args": { "_genkey_0": "/api/**", "_genkey_1": "/test/**" } } ], "filters": [ { "name": "Hystrix", "args": { "name": "default", "fallbackUri": "forward:/demo/fallback" } } ], "uri": "lb://jeecg-cloud-demo" } ] ``` filters部分为熔断配置 ### Spring cloud gateway熔断不重试问题 ![](https://img.kancloud.cn/fa/fb/fafbfc6a41434b312e7562308e731d1e_1044x678.png) ![](https://img.kancloud.cn/e6/88/e6882ec843d1d669685c521652f2bab4_1036x648.png) ### Spring cloud filters 说明 ![](https://img.kancloud.cn/0a/0b/0a0b7803647526fde7a635b68920bcee_1240x490.png) 部分过滤器说明 ![](https://img.kancloud.cn/64/6e/646eee1970b0984f4cc04ece96b53255_892x814.png) ![](https://img.kancloud.cn/9c/45/9c4555ba59c5d6e520b7755a2803fa54_893x656.png) ![](https://img.kancloud.cn/d4/b2/d4b2d32c322fb6e7462f6a731394bbb0_900x637.png) ![](https://img.kancloud.cn/77/a7/77a7618c30ecfbeb1f9bb3133886bbb6_893x437.png) ![](https://img.kancloud.cn/eb/8d/eb8dcb9f6288ce283ddfe218b82e12e6_898x425.png) ![](https://img.kancloud.cn/49/30/4930fc0ab4374d6ce46899ea07ef9461_909x337.png) [过滤器详解](https://blog.csdn.net/forezp/article/details/85057268) [ 视频教程](https://www.bilibili.com/video/BV1sZ4y1G7LL?p=8) ***** #### 限流配置 json路由配置 ``` { "name": "RequestRateLimiter", "args": { "key-resolver":"#{@ipKeyResolver}", "redis-rate-limiter.replenishRate": 20, "redis-rate-limiter.burstCapacity": 20 } } ``` xml路由配置 ``` spring: redis: host: localhost filters: # redis限流 , filter名称必须是RequestRateLimiter - name: RequestRateLimiter args: # 使用SpEL名称引用Bean,与上面新建的RateLimiterConfig类中的bean的name相同 key-resolver: '#{@ipKeyResolver}' # 每秒最大访问次数 redis-rate-limiter.replenishRate: 20 # 令牌桶最大容量 redis-rate-limiter.burstCapacity: 20 ``` 限流方式支持IP/用户接口等方式 ip限流:key-resolver: '#{@ipKeyResolver}' 用户限流:key-resolver: '#{@userKeyResolver}' 接口限流:key-resolver: '#{@apiKeyResolver}' #### 限流测试 模拟100个并发 ![](https://img.kancloud.cn/52/7f/527f143c239827162b22a91f907ca157_1138x644.png) 测试结果 ![](https://img.kancloud.cn/33/a1/33a1edccd53c91b4eb3deb48e8a53a73_1472x853.png)