通过路由可以定义已知的规则,但不可能考虑到所有用户的所有请求,而且路由设计可能存在变更,网络等基础设施可能产生错误,所以需要进行路由容错。路由容错主要通过未定义的路由和路由熔断来实现。
#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
@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);
}
}
1、访问:http://localhost:50024/hello?token=1
2、访问:http://localhost:50024/helloworld?token=1
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
#开启支持
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/
/***
* 当服务不可用时,触发
* @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);
}
关掉服务提供者,访问:http://localhost:50024/hello?token=1