spring-cloud-gateway降级

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

spring-cloud-gateway降级

当我遇上你csy   2020-04-08 我要评论
# 前言 本文主要研究一下 spring cloud gateway 如何集成 hystrix。 当下游接口负载很大,或者接口不通等其他原因导致超时,如果接口不熔断的话将会影响到下游接口得不到喘息,网关也会因为超时连接一直挂起,很可能因为一个子系统的问题导致整个系统的雪崩。所以我们的网关需要设计熔断,当因为熔断器打开时,网关将返回一个降级的应答。 # Maven 配置 添加 hystrix 依赖 pom.xml ```xml ``` # 项目实战 1. 在 `provider1` 服务中添加一个方法,延时 2 秒返回响应。 ```java @GetMapping("/timeout") public String timeout() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("休眠了2秒"); return "timeout test"; } ``` 2. 修改网关配置文件 ```yaml server: port: 2000 spring: application: name: idc-gateway2 redis: host: localhost port: 6379 timeout: 6000ms # 连接超时时长(毫秒) jedis: pool: max-active: 1000 # 连接池最大连接数(使用负值表示没有限制) max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制) max-idle: 10 # 连接池中的最大空闲连接 min-idle: 5 # 连接池中的最小空闲连接 cloud: consul: host: localhost port: 8500 gateway: discovery: locator: enabled: true # gateway可以通过开启以下配置来打开根据服务的serviceId来匹配路由,默认是大写 routes: - id: provider1 uri: lb://idc-provider1 predicates: - Path=/p1/** filters: - StripPrefix=1 - name: Hystrix args: name: default fallbackUri: forward:https://img.qb5200.com/download-x/defaultfallback # 只有该id下的服务会降级 - id: provider2 uri: lb://idc-provider2 predicates: - Path=/p2/** filters: - StripPrefix=1 # hystrix 信号量隔离,1.5秒后自动超时 hystrix: command: default: execution: isolation: strategy: SEMAPHORE thread: timeoutInMilliseconds: 1500 ``` 3. 网关添加降级处理类 ```java @RestController public class FallbackController { @RequestMapping("https://img.qb5200.com/download-x/defaultfallback") public Map

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们