网关(Gateway)- 自定义过滤器工厂

自定义过滤工厂类

DemoGatewayFilterFactory

java 复制代码
package com.learning.springcloud.custom;

import org.apache.commons.lang.StringUtils;
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.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

@Component
public class DemoGatewayFilterFactory extends AbstractGatewayFilterFactory<DemoGatewayFilterFactory.Config> {

    public DemoGatewayFilterFactory() {
        super(Config.class);
    }

    public List<String> shortcutFieldOrder() {
        return Arrays.asList("name", "value");
    }

    @Override
    public GatewayFilter apply(DemoGatewayFilterFactory.Config config) {
        return new GatewayFilter() {
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                String value = exchange.getRequest().getQueryParams().getFirst("name");

                if (StringUtils.isBlank(value)) {
                    // 为空 则证明是正常的请求 需要放行
                    return chain.filter(exchange);
                }
                if ("YES".equals(value)) {
                    return chain.filter(exchange);
                }
                exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND);
                return exchange.getResponse().setComplete();
            }
        };
    }

    public static class Config {
        private String name;
        private String value;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String name) {
            this.value = name;
        }
    }
}

过滤器配置说明

java 复制代码
server:
  port: 8088
spring:
  application:
    name: api-gateway
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8847
        username: nacos
        password: nacos
    gateway:
      routes:
        - id: order_route # 路由唯一标识
          #uri: http://localhost:8020 # 需要转发的地址
          uri: lb://order-service # 需要转发的地址
          # 断言规则  用于路由规则的匹配
          predicates:
#            - Path=/order-serv/**
#            - After=2024-01-01T23:00:11.518+08:00[Asia/Shanghai]
#            - Before=2025-01-01T23:00:11.518+08:00[Asia/Shanghai]
            - Between=2024-01-01T23:00:11.518+08:00[Asia/Shanghai],2025-01-01T23:00:11.518+08:00[Asia/Shanghai]
#            - Header=X-Request-Id,\d+
#            - Host=127.0.0.1
#            - Query=name,lq
#            - Method=GET,POST
            # http://localhost:8088/order-serv/order/add  => http://localhost:8020/order-serv/order/add
            - Demo=YES
          #配置过滤器工厂
          filters:
            - StripPrefix=1 # 转发去掉第一层路径
            - AddRequestHeader=X-Request-name,tom #添加请求头
            - AddRequestParameter=color, blue # 添加请求参数
            - PrefixPath=/demo
#            - RedirectTo=302, https://www.baidu.com/ #重定向到百度
            - Demo=name,YES  # 自定义过滤工厂配置
            # http://localhost:8020/order-serv/order/add => http://localhost:8020/order/add

访问效果

  • 不带name参数的请求放行
  • 带name参数值不是YES的拦截,返回 not found
  • 带name参数值是YES的放行

实现说明

  • 命名必须需要以 FilterFactory 结尾(约定规范)
  • 继承 AbstractGatewayFilterFactory 类
  • 必须为spring的组件bean(@Component)
  • 必须要有内部类 Config 以及 对应的 shortcutFieldOrder 方法
  • 重写 apply 方法的逻辑 (apply(DemoGatewayFilterFactory.Config config))
  • 可通过 exchange.getRequest() 获取到 ServerHttpRequest 对象
  • 从而获取到请求的参数、请求方式、请求头等信息
相关推荐
PXM的算法星球4 天前
spring gateway配合nacos实现负载均衡
spring·gateway·负载均衡
1990_super5 天前
使用ceph-deploy安装和配置RADOS Gateway (RGW)并使用S3访问集群
ceph·gateway
北极糊的狐8 天前
接口返回504 Gateway Time-out 错误,这意味着请求在网关或代理服务器等待上游服务器响应时超时。以下是可能的原因和排查建议:
数据库·gateway
sg_knight8 天前
Spring Cloud Gateway全栈实践:动态路由能力与WebFlux深度整合
java·spring boot·网关·spring·spring cloud·微服务·gateway
放纵日放纵11 天前
微服务—Gateway
微服务·架构·gateway
你我约定有三11 天前
分布式微服务--GateWay(1)
java·开发语言·分布式·微服务·架构·gateway
毛小茛12 天前
Spring Cloud Gateway 实现登录校验:构建统一认证入口
springcloud
William一直在路上14 天前
KONG API Gateway中的核心概念
网络·gateway·kong
●VON16 天前
重生之我在暑假学习微服务第七天《微服务之服务治理篇》
java·学习·微服务·云原生·nacos·架构·springcloud