赞
踩
目录
四、继承AbstractGatewayFilterFactory
当使用Spring Cloud Gateway构建API网关时,可以利用Spring Cloud Gateway提供的内置过滤器(filter)来实现对请求的处理和响应的处理。过滤器可以在请求被路由之前或之后被执行,它可以用于修改请求和响应内容、记录请求日志、校验请求参数、鉴权等等。如果内置的过滤器不能满足需求,可以自定义过滤器。
之前博客已经介绍了Spring Cloud Gateway内置过滤器的使用方法和示例,具体可以参考:https://blog.csdn.net/qq_41061437/article/details/128069622
本篇博客将重点介绍如何编写自定义的过滤器,并将其应用到Spring Cloud Gateway中。将使用Java编程语言,以及Spring Boot和Spring Cloud Gateway框架。将通过一个示例来演示如何实现一个自定义过滤器,讲解自定义过滤器的实现方法、配置方法和使用方法。
SpringCloudGateWay项目参考:SpringCloudGateway--自动路由映射与手动路由映射_雨欲语的博客-CSDN博客
全局过滤器需要实现GlobalFilter和Ordered,在gateway项目中新建MyGlobalFilter类:
- import org.springframework.cloud.gateway.filter.GatewayFilterChain;
- import org.springframework.cloud.gateway.filter.GlobalFilter;
- import org.springframework.core.Ordered;
- import org.springframework.http.HttpStatus;
- import org.springframework.stereotype.Component;
- import org.springframework.web.server.ServerWebExchange;
- import reactor.core.publisher.Mono;
-
- import java.util.Optional;
-
- /**
- * @Author dengyifan
- * @create 2023/11/7 14:12
- * @description
- */
- @Component
- public class MyGlobalFilter implements GlobalFilter, Ordered {
- @Override
- public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
- // 获取请求路径
- System.err.println(String.format("全局过滤器获取到请求路径:%s", exchange.getRequest().getURI()));
- String test = exchange.getRequest().getHeaders().getFirst("test");
- // 无test请求头
- if (!Optional.ofNullable(test).isPresent()) {
- System.err.println("无指定请求头");
- exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
- return exchange.getResponse().setComplete();
- }
- System.err.println(String.format("请求头参数:%s", test));
- return chain.filter(exchange);
- }
-
- @Override
- public int getOrder() {
- return 0;
- }
- }
配置文件不需要进行修改,postman进行测试,首先是不含test请求头的:
添加请求头后:
使用GatewayFilter实现需要implements GatewayFilter和Ordered,在gateway项目中新建MyOneGatewayFilter类:
- import org.springframework.cloud.gateway.filter.GatewayFilter;
- import org.springframework.cloud.gateway.filter.GatewayFilterChain;
- import org.springframework.core.Ordered;
- import org.springframework.http.server.reactive.ServerHttpRequest;
- import org.springframework.stereotype.Component;
- import org.springframework.web.server.ServerWebExchange;
- import reactor.core.publisher.Mono;
-
- import java.net.URI;
-
- @Component
- public class MyOneGatewayFilter implements GatewayFilter, Ordered {
- @Override
- public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
- // 获取请求路径
- String path = exchange.getRequest().getPath().toString();
- URI uri = exchange.getRequest().getURI();
- System.err.println(String.format("获取到请求路径:%s", uri.toString()));
- // 如果请求路径以“/v1”开头,则截取掉第一个路径段
- if (path.startsWith("/v1")) {
- path = path.substring("/v1".length());
- }
-
- // 创建新的请求对象,并将新路径设置为请求路径
- ServerHttpRequest newRequest = exchange.getRequest().mutate()
- .path(path)
- .build();
-
- // 使用新请求对象创建新的ServerWebExchange对象
- ServerWebExchange newExchange = exchange.mutate()
- .request(newRequest)
- .build();
- System.err.println(String.format("获取到新的请求路径:%s", newExchange.getRequest().getURI()));
- // 继续执行过滤器链
- return chain.filter(newExchange);
- }
-
- @Override
- public int getOrder() {
- return 0;
- }
- }
新建GatewayConfig类,
- import com.littledyf.filter.MyOneGatewayFilter;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.cloud.gateway.route.RouteLocator;
- import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
-
-
- @Configuration
- public class GatewayConfig {
-
- @Value("${server.port}")
- private String port;
-
- @Bean
- public RouteLocator customerRouteLocator(RouteLocatorBuilder builder) {
- return builder.routes()
- .route(r -> r.path("/v1/**")
- .filters(f -> f.filter(new MyOneGatewayFilter()))
- .uri("http://localhost:" + port)
- )
- .build();
- }
-
- }
yml文件使用之前的:
server: port: 9999 spring: application: name: service-gateway cloud: # 配置Spring Cloud相关属性 gateway: discovery: # 配置网关发现机制 locator: # 配置处理机制 enabled: false # 开启网关自动映射处理逻辑 lower-case-service-id: true # 开启小写转换 filter: secure-headers: disable: - strict-transport-security - x-download-options routes: # 配置网关中的一个完整路由,包括命名,地址,谓词集合(规则),过滤器集合 - id: service-one # 路由定义的命名,唯一即可。命名规则符合Java中的变量符命名规则 uri: lb://service-one # 当前路由定义对应的微服务转发地址,lb - 代表loadbalance predicates: # 配置谓词集合 - Path=/service/** filters: - StripPrefix=1 nacos: username: nacos password: nacos discovery: server-addr: 127.0.0.1 group: dev namespace: dev metadata: version: v1.0.0
启动项目访问测试:http://localhost:9999/v1/service/nacos/test
可以看到如果是以v1开头的,会直接进入到我们自定义的MyOneGatewayFilter过滤器中,如果直接service开头,则直接走内置过滤器。
xxxxGatewayFilterFactory是符合内置过滤器原则的,所有已经实现的内置过滤器都是按照这种方式进行的,这里就是仿照内置过滤器编写,编写MyTwoGatewayFilterFactory类:
- import org.springframework.cloud.gateway.filter.GatewayFilter;
- import org.springframework.cloud.gateway.filter.GatewayFilterChain;
- import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
- import org.springframework.cloud.gateway.support.GatewayToStringStyler;
- import org.springframework.http.server.reactive.ServerHttpRequest;
- import org.springframework.stereotype.Component;
- import org.springframework.web.server.ServerWebExchange;
- import reactor.core.publisher.Mono;
-
- import java.net.URI;
- import java.util.Arrays;
- import java.util.List;
-
- @Component
- public class MyTwoGatewayFilterFactory extends AbstractGatewayFilterFactory<MyTwoGatewayFilterFactory.Config> {
- public MyTwoGatewayFilterFactory() {
- super(MyTwoGatewayFilterFactory.Config.class);
- }
-
- @Override
- public List<String> shortcutFieldOrder() {
- return Arrays.asList("name");
- }
-
- @Override
- public GatewayFilter apply(MyTwoGatewayFilterFactory.Config config) {
- return new GatewayFilter() {
- @Override
- public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
- // 获取请求路径
- URI uri = exchange.getRequest().getURI();
- System.err.println(String.format("获取到请求路径:%s", uri));
- //
- System.err.println(String.format("配置属性:%s", config.getName()));
- String path = exchange.getRequest().getPath().toString();
- // 如果请求路径以“/xxx”开头,则截取掉第一个路径段,xxx是配置文件中的name属性
- if (path.startsWith("/" + config.getName())) {
- path = path.substring(("/" + config.getName()).length());
- }else {
- throw new IllegalStateException("CustomGatewayFilter is not enabled");
- }
-
- // 创建新的请求对象,并将新路径设置为请求路径
- ServerHttpRequest newRequest = exchange.getRequest().mutate()
- .path(path)
- .build();
-
- // 使用新请求对象创建新的ServerWebExchange对象
- ServerWebExchange newExchange = exchange.mutate()
- .request(newRequest)
- .build();
- System.err.println(String.format("获取到新的请求路径:%s", newExchange.getRequest().getURI()));
-
- return chain.filter(newExchange);
- }
-
- @Override
- public String toString() {
- return GatewayToStringStyler.filterToStringCreator(MyTwoGatewayFilterFactory.this).toString();
- }
- };
- }
-
- public static class Config {
- private String name;
-
- public Config() {
- }
-
- public String getName() {
- return this.name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
- }
- }
在配置文件中加上刚编写的自定义过滤器名:
server: port: 9999 spring: application: name: service-gateway cloud: # 配置Spring Cloud相关属性 gateway: discovery: # 配置网关发现机制 locator: # 配置处理机制 enabled: false # 开启网关自动映射处理逻辑 lower-case-service-id: true # 开启小写转换 filter: secure-headers: disable: - strict-transport-security - x-download-options routes: # 配置网关中的一个完整路由,包括命名,地址,谓词集合(规则),过滤器集合 - id: service-one # 路由定义的命名,唯一即可。命名规则符合Java中的变量符命名规则 uri: lb://service-one # 当前路由定义对应的微服务转发地址,lb - 代表loadbalance predicates: # 配置谓词集合 - Path=/service/** filters: - StripPrefix=1 - MyTwo=api nacos: username: nacos password: nacos discovery: server-addr: 127.0.0.1 group: dev namespace: dev metadata: version: v1.0.0
测试:http://localhost:9999/service/api/nacos/test
如果不包含我们定义的api,则直接报错:
这只是简单展示了自定义过滤器的功能,实际能实现很多复杂功能。比如进行鉴权、黑白名单过滤等等。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。