使用Spring Cloud Gateway在代理服务器中声明固定负载

问题描述 投票:0回答:1

我正在 Spring Cloud Gateway 中的 api 使用代理网关,对于其中一个请求,我想传递一个有效负载而不从用户那里获取它,并且应该传递一个修复有效负载

例如 {“Fname”:“abc”, “L名称”:“xyz” }

我通过 application.yaml 使用代理网关

spring:

  cloud:

    gateway:

      routes:

        - id: example_route

          uri: http://example.com

          predicates:

            - Path=/example/**

          filters:

            - RewritePath=/example/(?

有人可以帮忙怎么做吗

spring spring-cloud-gateway
1个回答
0
投票
  1. 编写自定义过滤器以在发送到目标 URI 之前设置固定有效负载:
公共类FixedPayloadGatewayFilterFactory扩展AbstractGatewayFilterFactory {

    @覆盖
    公共网关过滤器应用(配置配置){
        返回(交换,链)-> {
            String Payload = "{\"Fname\": \"abc\", \"Lname\": \"xyz\"}";

            // 使用固定负载修改请求
            ServerHttpRequest ModifiedRequest = Exchange.getRequest().mutate()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                    .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(payload.length()))
                    .body(payload.getBytes(StandardCharsets.UTF_8))
                    。建造();

            // 使用修改后的请求创建一个新的交换对象
            ServerWebExchange ModifiedExchange = Exchange.mutate().request(modifiedRequest).build();

            return chain.filter(modifiedExchange);
        };
    }
}
  1. 将此自定义过滤器添加到您的路线中
    application.yaml
    :
春天:
  云:
    网关:
      路线:
        - id: 示例_路线
          网址:http://example.com
          谓词:
            - 路径=/示例/**
          过滤器:
            - 名称:固定有效负载

参考:创建自定义 Spring Cloud Gateway Filter

© www.soinside.com 2019 - 2024. All rights reserved.