阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

实现路由容错

122次阅读
没有评论

共计 2257 个字符,预计需要花费 6 分钟才能阅读完成。

1、实现路由容错

通过路由可以定义已知的规则,但不可能考虑到所有用户的所有请求,而且路由设计可能存在变更,网络等基础设施可能产生错误,所以需要进行路由容错。路由容错主要通过未定义的路由和路由熔断来实现。

2、处理未定义路由

2.1、添加路由配置

#id: 自定义路由 ID
spring.cloud.gateway.routes[1].id=notfound_route1
#uri: 目标服务地址
spring.cloud.gateway.routes[1].uri=forward:/notfound
#predicates: 路由条件。Predicate 根据输入参数返回一个布尔值。其包含多种默认方法来将 Predicate 组合成复杂的路由逻辑
spring.cloud.gateway.routes[1].predicates[0]=Path=/**
#id: 自定义路由 ID
spring.cloud.gateway.routes[0].id=addrequestheader_route1
#uri: 目标服务地址
spring.cloud.gateway.routes[0].uri=http://localhost:50006
#predicates: 路由条件。Predicate 根据输入参数返回一个布尔值。其包含多种默认方法来将 Predicate 组合成复杂的路由逻辑
spring.cloud.gateway.routes[0].predicates[0]=Path=/hello

2.2、编写路由容错控制器

@RestController public class NotFoundController {/*** * 当没匹配到路由时使用,用来返回信息 * @return */ @RequestMapping(value = "/notfound") public Mono<Map<String, String>> notFound() {Map<String, String> stringMap = new HashMap<>(); stringMap.put("code", "404"); stringMap.put("data", "found"); return Mono.just(stringMap); } }

2.3、测试

1、访问:http://localhost:50024/hello?token=1

实现路由容错

2、访问:http://localhost:50024/helloworld?token=1

实现路由容错

3、用 Hystrix 处理路由熔断

3.1、添加依赖

<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>

3.2、添加配置

# 开启支持
feign.hystrix.enabled=true
#id: 自定义路由 ID
spring.cloud.gateway.routes[2].id=hystrix_route1
#uri: 目标服务地址
spring.cloud.gateway.routes[2].uri=lb://OPEN-FEIGN
#predicates: 路由条件。Predicate 根据输入参数返回一个布尔值。其包含多种默认方法来将 Predicate 组合成复杂的路由逻辑
spring.cloud.gateway.routes[2].predicates[0]=Path=/hello
#过滤器的名字,Gagteway 将用 Hystrix 作为名称生成 HystrixCommand 对象进行熔断管理
spring.cloud.gateway.routes[0].filters[0].name=Hystrix
spring.cloud.gateway.routes[0].filters[0].args.name=fallbackcmd
#配置了 fallback 时要回调路径。当 Hystrix 的 fallback 被调用时,请求将转发到 fallback
#这里的 fallback 是在路由控制器中定义的方法
spring.cloud.gateway.routes[0].filters[0].args.fallbackUri=forward:/fallback
#注册中心地址
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=true
eureka.client.service-url.defaultZone=http://eureka01:50025/eureka/,http://eureka02:50026//eureka/

3.3、编写路由容错控制器

/*** * 当服务不可用时,触发 * @return */ @GetMapping("/fallback") public Mono<Map<String,String>> fallback(){Map<String, String> stringMap = new HashMap<>(); stringMap.put("code", "100"); stringMap.put("data", "Service Not Available"); return Mono.just(stringMap); }

3.4、测试

关掉服务提供者,访问:http://localhost:50024/hello?token=1
实现路由容错

正文完
星哥说事-微信公众号
post-qrcode
 
星锅
版权声明:本站原创文章,由 星锅 2022-06-06发表,共计2257字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中