#### 微服务熔断/降级/限流——全局配置 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部分为熔断配置 #### 限流配置 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)