spring cloud gateway 动态修改请求

最后发布时间:2024-11-14 09:36:53 浏览量:
  • https://blog.csdn.net/weixin_40912627/article/details/107381180
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
 
import java.net.URI;
 
@Component
public class ModifyRequestGlobalFilter implements GlobalFilter, Ordered {
 
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取原始请求
        ServerHttpRequest request = exchange.getRequest();
 
        // 修改请求路径,例如添加一个路径片段
        String modifiedPath = request.getPath().pathWithinApplication()
                                     .value() + "/modified";
 
        // 构建新的请求
        ServerHttpRequest newRequest = request.mutate()
                                             .path(modifiedPath)
                                             .build();
 
        // 返回修改后的请求
        return chain.filter(exchange.mutate().request(newRequest).build());
    }
 
    @Override
    public int getOrder() {
        // 确保此全局过滤器在其他过滤器之前运行
        return -1;
    }
}

https://github.com/spring-cloud/spring-cloud-gateway/issues/59

public class HeaderFilterFactory implements WebFilterFactory {
    @Override
    public WebFilter apply(Tuple args) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest().mutate().build();
            request.getHeaders().add("Connection", "Upgrade");
            request.getHeaders().add("Upgrade", "websocket");
            request.getHeaders().add("Sec-WebSocket-Protocol", "base64.channel.k8s.io");
            return chain.filter(exchange.mutate().request(request).build());
        };
    }
}
快捷入口
java 思维导图 浏览PDF 下载PDF
分享到:
标签