文章目录
1 Route Predicate Factories
1.1 The After Route Predicate Factory
在指定时间后的请求将被路由,这里的时间使用的是Java的ZonedDateTime
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://www.baidu.com
predicates:
- After=2020-12-13T11:29:07.057+08:00[Asia/Shanghai]
在地址栏输入http://localhost:8080/,可以看到被路由到了百度
还有before,between使用方法类似
1.2 The Cookie Route Predicate Factory
携带指定cookie的请求将被路由。参数有两个,前者是name,后者是value,value可以使用正则表达式。
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://www.baidu.com
predicates:
- Cookie=chocolate, ch.p
使用命令curl -b “chocolate=chap” localhost:8080 可以获取到b百度的页面
curl -b “chocolate=chp” localhost:8080 则无法获取
其它的根据header自定义字段,host字段,path等使用方法类似
1.3 The Weight Route Predicate Factory
可以通过权重给路由地址分流,这里具体不好演示,但经过测试,在这种配置下,路由到https://weighthigh.org的请求占80%,路由到https://weightlow.org的占20%
spring:
cloud:
gateway:
routes:
- id: weight_high
uri: https://weighthigh.org
predicates:
- Weight=group1, 8
- id: weight_low
uri: https://weightlow.org
predicates:
- Weight=group1, 2
2 GatewayFilter Factories
filter也是springcloud gateway的重要部分,它分为前后两部分,在请求到达服务前和请求从服务返回后两个时间点,分别对请求进行处理。
这里我先启动一个8082端口的应用,主要作用是打印请求的header和param
@RestController
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@GetMapping("/listHeaders")
public ResponseEntity<String> listAllHeaders(@RequestHeader Map<String, String> headers) {
headers.forEach((key, value) -> {
System.out.println(String.format("Header '%s' = %s", key, value));
});
return new ResponseEntity<String>(String.format("Listed %d headers", headers.size()), HttpStatus.OK);
}
@RequestMapping(value="/listParams")
public String bar(@RequestParam MultiValueMap<String, String> parameters){
parameters.forEach((key, value)->{
System.out.println(String.format("Param '%s' = %s", key, value));
});
return String.format("Listed %d params", parameters.size());
}
}
2.1 The AddRequestHeader GatewayFilter Factory
spring:
cloud:
gateway:
routes:
- id: add_request_header_route
uri: http://localhost:8082
predicates:
- Path=/{segment}
filters:
- AddRequestHeader=X-Request-red, blue
使用命令 curl -H “X-Request-red:blue” localhost:8080/listHeaders 可以看到控制台打印的头信息中含有添加的字段
还有很多的filter,比如在请求中加入param,在请求放回时删除一些头信息等,使用方法都类似。