日常小记:springcloud gateway使用

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,在请求放回时删除一些头信息等,使用方法都类似。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值