共计 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、编写路由容错控制器
public class NotFoundController {/*** | |
* 当没匹配到路由时使用,用来返回信息 | |
* @return | |
*/ | |
"/notfound") | (value =|
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 | |
spring.cloud.gateway.routes[2].id=hystrix_route1 | |
spring.cloud.gateway.routes[2].uri=lb://OPEN-FEIGN | |
spring.cloud.gateway.routes[2].predicates[0]=Path=/hello | |
spring.cloud.gateway.routes[0].filters[0].name=Hystrix | |
spring.cloud.gateway.routes[0].filters[0].args.name=fallbackcmd | |
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 | |
*/ | |
"/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
正文完
星哥玩云-微信公众号
