跳到主要内容 Spring Cloud Gateway Web MVC 使用指南 | 极客日志
Java java
Spring Cloud Gateway Web MVC 使用指南 基于 Spring Boot 的 Spring Cloud Gateway Web MVC 特性。内容涵盖工程搭建、路由配置(配置文件与 Java 编程方式)、自定义过滤器及谓词的实现与使用,以及效果验证。通过示例代码展示了如何配置路由、添加请求头参数及处理请求逻辑,帮助开发者掌握网关的基本到深入应用。
DataScient 发布于 2026/4/5 更新于 2026/4/13 1 浏览Spring Cloud Gateway Web MVC 使用指南
前言
本文提供了对 Spring Cloud Gateway Web MVC 特性的使用案例,涵盖了从工程搭建及基本使用至概念理解再到一些自定义客制化的使用。所配关键代码都有注释。
一、前置条件
二、工程搭建
创建一个普通 Maven 工程,添加必要依赖及构建工具即可,本案例是一个 Maven 子工程。
父工程 pom.xml (仅列出关键依赖)
pom.xml 文件
<?xml version="1.0" encoding="UTF-8" ?>
<project xmlns ="http://maven.apache.org/POM/4.0.0"
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation ="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >
<parent >
<artifactId > springCloudMicroService</artifactId >
<groupId > org.example</groupId >
<version > 1.0-SNAPSHOT</version >
</parent >
<modelVersion > 4.0.0</modelVersion >
< > gatewayServerWebMvcDemo
17
17
UTF-8
UTF-8
org.springframework.cloud
spring-cloud-starter-gateway-server-webmvc
org.springframework.boot
spring-boot-starter-test
test
org.apache.maven.plugins
maven-compiler-plugin
true
org.springframework.boot
spring-boot-maven-plugin
3.5.8
${start-class}
JAR
repackage
org.apache.maven.plugins
maven-resources-plugin
3.1.0
${}
false
src/main/resources
true
public/**
static/**
templates/**
mapper/**
properties/**
i18n/**
logback*.xml
application.yml
application-${spring.profiles.active}.*
log*-${spring.profiles.active}.xml
dev
dev
true
sit
sit
false
prod
prod
false
微信扫一扫,关注极客日志 微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
相关免费在线工具 Keycode 信息 查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online
Escape 与 Native 编解码 JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online
JavaScript / HTML 格式化 使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online
JavaScript 压缩与混淆 Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online
Base64 字符串编码/解码 将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
Base64 文件转换器 将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
artifactId
</artifactId >
<properties >
<maven.compiler.source >
</maven.compiler.source >
<maven.compiler.target >
</maven.compiler.target >
<project.build.sourceEncoding >
</project.build.sourceEncoding >
<project.reporting.outputEncoding >
</project.reporting.outputEncoding >
</properties >
<dependencies >
<dependency >
<groupId >
</groupId >
<artifactId >
</artifactId >
</dependency >
<dependency >
<groupId >
</groupId >
<artifactId >
</artifactId >
<scope >
</scope >
</dependency >
</dependencies >
<build >
<plugins >
<plugin >
<groupId >
</groupId >
<artifactId >
</artifactId >
<configuration >
<parameters >
</parameters >
</configuration >
</plugin >
<plugin >
<groupId >
</groupId >
<artifactId >
</artifactId >
<version >
</version >
<configuration >
<mainClass >
</mainClass >
<layout >
</layout >
</configuration >
<executions >
<execution >
<goals >
<goal >
</goal >
</goals >
</execution >
</executions >
</plugin >
<plugin >
<groupId >
</groupId >
<artifactId >
</artifactId >
<version >
</version >
<configuration >
<delimiters >
<delimiter >
</delimiter >
</delimiters >
<useDefaultDelimiters >
</useDefaultDelimiters >
<resources >
<resource >
<directory >
</directory >
<filtering >
</filtering >
<includes >
<include >
</include >
<include >
</include >
<include >
</include >
<include >
</include >
<include >
</include >
<include >
</include >
<include >
</include >
<include >
</include >
<include >
</include >
<include >
</include >
</includes >
</resource >
</resources >
</configuration >
</plugin >
</plugins >
</build >
<profiles >
<profile >
<id >
</id >
<properties >
<spring.profiles.active >
</spring.profiles.active >
</properties >
<activation >
<activeByDefault >
</activeByDefault >
</activation >
</profile >
<profile >
<id >
</id >
<properties >
<spring.profiles.active >
</spring.profiles.active >
</properties >
<activation >
<activeByDefault >
</activeByDefault >
</activation >
</profile >
<profile >
<id >
</id >
<properties >
<spring.profiles.active >
</spring.profiles.active >
</properties >
<activation >
<activeByDefault >
</activeByDefault >
</activation >
</profile >
</profiles >
</project >
三、功能实现范围
配置文件或 Java 编程方式的路由配置
自定义过滤器(Filter)、自定义谓词(Predicate)的实现与使用
路由到本服务接口(用于 Spring MVC 的函数式端点的使用)
四、需要路由访问的服务(应用)准备
五、路由配置(配置文件方式) server:
server-name: gatewaymvcdemo
port: 8888
spring:
profiles:
active: fileconfig
路由配置文件(application-fileconfig.yml)
spring:
cloud:
gateway:
server:
webmvc:
routes:
- id: function_demo_route
uri: http://localhost:8082
predicates:
- Method=GET,PUT,DELETE,POST
- Path=/functionservletpath/**
filters:
- AddRequestParameter=code,gateway for functiondemo
- AddRequestHeader=function-Request-Id,function_header_value
- id: entitle_route
uri: http://localhost:8081
predicates:
- Method=GET,PUT,DELETE,POST
- Path=/entitleservice/info/**,/entitleservice/gatewayInfo/**,/entitleservice/user/**,/entitleservice/role/**
filters:
- AddRequestParameter=code,gateway for entitleservice
- AddRequestHeader=entitle-Request-Id,entitle_header_value
- instrumentForFilter=req_header,rep_header
六、路由配置(Java 编程方式) server:
server-name: gatewaymvcdemo
port: 8888
spring:
profiles:
active: javaconfig
java 配置文件(ApplicationRoutingConfig.java)
package com.mrhan.config;
import com.mrhan.service.GatewayHandler;
import com.mrhan.service.UserHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.function.*;
import java.time.ZonedDateTime;
import java.util.function.BiFunction;
import java.util.function.Function;
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.*;
import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route;
import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http;
import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.*;
import static org.springframework.web.servlet.function.RequestPredicates.accept;
@Configuration(proxyBeanMethods = false)
@Profile("javaconfig")
public class ApplicationRoutingConfig {
private static final Logger log = LoggerFactory.getLogger(ApplicationRoutingConfig.class);
@Bean
public RouterFunction<ServerResponse> customRoutes (GatewayHandler gatewayHandler) {
return route("path_route" )
.GET("/gateway/getRole" , accept(MediaType.TEXT_HTML), gatewayHandler::getRole)
.POST("/gateway/updateRole/{roleId}" , accept(MediaType.APPLICATION_JSON), gatewayHandler::updateRole)
.before(request -> {
String path = request.requestPath().value();
log.error("=========开始进入本服务请求:{}=========" , path);
return request;
})
.after((request, response) -> {
log.error("==========本服务请求处理完毕:{},响应的状态码:" , request.requestPath().value(), response.statusCode());
return response;
})
.build()
.and(route("entitle_route" )
.route(path("/entitleservice/**" ).and(SampleRequestPredicates.predicateHeaderExists("entitle_header" )), http())
.before(uri("http://localhost:8081" ))
.before(addRequestParameter("code" , "Java gateway for entitlementservice" ))
.before(addRequestHeader("java_config_header" , "java config value" ))
.filter(SampleHandlerFilterFunctions.instrumentForFilter("req_header" , "rep_header" ))
.build())
.and(route("function_demo_route" )
.route(path("/functionservletpath/**" ).and(SampleRequestPredicates.predicateHeaderExists("function_header" )), http())
.before(uri("http://localhost:8082" ))
.before(addRequestParameter("code" , "Java config gateway for functiondemo" ))
.before(addRequestHeader("function-Request-Id" , "function_header_value" ))
.build());
}
private static class CustomHeaderExists implements RequestPredicate {
private static final String HEADER_NAME = "custom_header" ;
@Override
public boolean test (ServerRequest request) {
return request.headers().asHttpHeaders().containsKey(HEADER_NAME);
}
}
private static HandlerFilterFunction<ServerResponse, ServerResponse> instrumentWithFilter (String requestHeader, String responseHeader) {
return (request, next) -> {
ServerRequest modifier = ServerRequest.from(request).header(requestHeader, "hello" ).build();
ServerResponse responseHandler = next.handle(modifier);
responseHandler.headers().add(responseHeader, "world" );
return responseHandler;
};
}
private static Function<ServerRequest, ServerRequest> instrumentWithBefore (String requestHeader) {
return request -> {
return ServerRequest.from(request).header(requestHeader, "before_header_value" ).build();
};
}
private static BiFunction<ServerRequest, ServerResponse, ServerResponse> instrumentWithAfter (String header) {
return (request, response) -> {
response.headers().add(header, "after_header_value" );
return response;
};
}
}
七、自定义过滤器 过滤器定义(SampleHandlerFilterFunctions.java)
package com.mrhan.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.server.mvc.common.Configurable;
import org.springframework.cloud.gateway.server.mvc.common.Shortcut;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.function.HandlerFilterFunction;
import org.springframework.web.servlet.function.ServerRequest;
import org.springframework.web.servlet.function.ServerResponse;
import java.util.Objects;
import java.util.function.Function;
public class SampleHandlerFilterFunctions {
private static final Logger log = LoggerFactory.getLogger(SampleHandlerFilterFunctions.class);
@Shortcut
public static HandlerFilterFunction<ServerResponse, ServerResponse> instrumentForFilter (String reqHeaderName, String repHeaderName) {
return (request, next) -> {
log.error("==========进入自定义 filter 处理逻辑,请求头:{},响应头{}===========" , reqHeaderName, repHeaderName);
ServerRequest modified = ServerRequest.from(request).header(reqHeaderName, "request header for filter" ).build();
ServerResponse response = next.handle(modified);
response.headers().add(repHeaderName, "response header for filter" );
return response;
};
}
}
过滤器提供者(CustomFilterSupplier.java)
package com.mrhan.config;
import org.springframework.cloud.gateway.server.mvc.filter.SimpleFilterSupplier;
public class CustomFilterSupplier extends SimpleFilterSupplier {
public CustomFilterSupplier () {
super (SampleHandlerFilterFunctions.class);
}
}
过滤器配置类(FilterConfiguration.java)
package com.mrhan.config;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
@Profile("fileconfig")
public class FilterConfiguration {
private static final Logger log = LoggerFactory.getLogger(FilterConfiguration.class);
@PostConstruct
public void init () {
log.error("========开始加载 FilterConfiguration 配置============" );
}
@Bean
public CustomFilterSupplier customFilterSupplier () {
return new CustomFilterSupplier ();
}
}
八、自定义谓词 谓词定义(SampleRequestPredicates.java)
package com.mrhan.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.server.mvc.common.Configurable;
import org.springframework.cloud.gateway.server.mvc.common.Shortcut;
import org.springframework.web.servlet.function.RequestPredicate;
public class SampleRequestPredicates {
private static final Logger log = LoggerFactory.getLogger(SampleRequestPredicates.class);
@Shortcut
public static RequestPredicate predicateHeaderExists (String name) {
log.error("======进入了自定义 predicate 的处理逻辑所需请求头:{}==========" , name);
return request -> {
return request.headers().asHttpHeaders().containsKey(name);
};
}
}
谓词提供者(CustomPredicateSupplier.java)
package com.mrhan.config;
import org.springframework.cloud.gateway.server.mvc.predicate.PredicateSupplier;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
public class CustomPredicateSupplier implements PredicateSupplier {
@Override
public Collection<Method> get () {
return Arrays.asList(SampleRequestPredicates.class.getMethods());
}
}
谓词配置类(PredicateConfiguration.java)
package com.mrhan.config;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.server.mvc.predicate.PredicateSupplier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
@Profile("fileconfig")
public class PredicateConfiguration {
private static final Logger log = LoggerFactory.getLogger(PredicateConfiguration.class);
@PostConstruct
public void init () {
log.error("========开始加载 PredicateConfiguration 配置============" );
}
@Bean
public CustomPredicateSupplier customPredicateSupplier () {
return new CustomPredicateSupplier ();
}
}
九、自定义谓词、自定义过滤器的使用 配置文件方式:格式 "静态方法名(首字母大写小写都可)=参数值"
十、效果验证(配置文件方式的路由效果)
十一、一些疑问、困惑的解释
配置中的 uri 是干嘛的?
解释:处理转发过来的请求的服务器地址
怎么理解网关?
解释:将匹配(含你定义的请求路径、携带了某个请求头、请求参数等)你谓词(predicate)的请求经过一系列处理(过滤器的路径重写、添加请求头、参数等)后转给你指定的处理器(可能是访问的服务地址,可能是你指定处理该请求的一个方法)做处理,是请求访问的守门员。
总结 本文介绍了基于 Spring Boot 的 Spring Cloud Gateway Web MVC 特性,涵盖工程搭建、路由配置(配置文件与 Java 编程方式)、自定义过滤器及谓词的实现与使用,以及效果验证。通过示例代码展示了如何配置路由、添加请求头参数及处理请求逻辑,帮助开发者掌握网关的基本到深入应用。