美文网首页
Gateway网关过滤器

Gateway网关过滤器

作者: 冲鸭_程序猿 | 来源:发表于2021-05-30 11:19 被阅读0次

spirngcloud Gateway根据作用范围划分为 GatewayFilter 和 GlobalFilter,二者区别如下:
GatewayFilter:网关过滤器,需要通过 spring.cloud.routes.filters 配置在具体路由下,只作用在当前路由上或通过spirng.cloud.default-filters 配置在全局,作用在所有路由上。
GlobalFilter:全局过滤器,不需要在配置文件中配置,作用在所有的路由上,最终通过 GatewayFilterAdapter 包装成 GatewayFilterChain 可识别的过滤器,它为请求业务以及路由的 URI 转换为真实业务服务请求地址的核心过滤器,不需要配置系统初始化时加载,并作用在每个路由上。

1. 网关过滤器GatewayFilter

网关过滤器用于拦截并链式处理web请求,可以实现横切与应用无关的需求,比如:安全、访问超时的设置等。修改传入的HTTP请求或传出HTTP响应。Spring Cloud Gateway 包含许多内置的网关过滤器工厂一共有22个,包括头部过滤器、路径过滤器、Hystrix过滤器和重写请求URL的过滤器,还有参数和状态码等其他类型的过滤器,根据过滤器工厂的用途来划分,可以分为以下几种:Header、Parameter、Path、Body、Status、Session、Redirect、Retry、RateLimiter和Hystrix。

1.1 path过滤器

Path 路径过滤器可以实现URL重写,通过重新URL可以实现隐藏实际路径提高安全性,易于用户记忆和键入,易于被搜索引擎收录等优点,实现方式如下:

1.1.1 RewriterPathGatewayFilterFactory

RewritePath 网关过滤器工厂采用路径正则表达式参数和替换参数,使用Java正则表达式来灵活地重写请求路径。

spring:
  application:
    name: gateway-server
  cloud:
    gateway:
      # 路由规则
       routes:
          - id: product-service   # 路由ID,唯一,一般为各个服务名称
           uri: http://localhost:7070/ #目标URI,路由到微服务的地址
           predicates:
               # 匹配对应的URL请求,将匹配到的请求追加在目标 URI 之后
               - Path=/product/** , /api-gateway/**
            filters:  # 网关过滤器
                # 将 /api-gateway/product/1 重写为 /product/1
                - RewritePath=/api-gateway(?<segment>/?.*), $\{segment}
RewritePath=/api-gateway(?<segment>/?.*), $(segment)

1.1.2 PrefixPathGatewayFilterFactory

PrefixPath 网关过滤器工厂为匹配的 URI 添加指定前缀。

spring:
  application:
    name: gateway-server
  cloud:
    gateway:
      # 路由规则
       routes:
          - id: product-service   # 路由ID,唯一,一般为各个服务名称
           uri: http://localhost:7070/ #目标URI,路由到微服务的地址
           predicates:
               # 匹配对应的URL请求,将匹配到的请求追加在目标 URI 之后
               - Path=/**
            filters:  # 网关过滤器
                # 将 /1 重写为 /product/1
                - PrefixPath=/product
PrefixPath=/product

1.1.3 StripPrefixGatewayFilterFactory

StripPrefix 网关过滤器工厂采用一个参数 StripPrefix,该参数表示在将请求发送到下游之前从请求中剥离的路径个数。

spring:
  application:
    name: gateway-server
  cloud:
    gateway:
      # 路由规则
       routes:
           - id: product-service   # 路由ID,唯一,一般为各个服务名称
           uri: http://localhost:7070/ #目标URI,路由到微服务的地址
           predicates:
               # 匹配对应的URL请求,将匹配到的请求追加在目标 URI 之后
               - Path=/**
           filters:  # 网关过滤器
                # 将 /api/123/product/1 重写为 /product/1
                - StripPrefix=2
StripPrefix=2

1.1.4 SetPathGatewayFilterFactory

SetPath 网关过滤器工厂采用路径模板参数,它提供了一种通过允许模板化路径段来操作请求路径的简单方法,使用了SpringFramework中的URi模板,允许多个匹配段。

spring:
  application:
    name: gateway-server
  cloud:
    gateway:
      # 路由规则
       routes:
           - id: product-service   # 路由ID,唯一,一般为各个服务名称
           uri: http://localhost:7070/ #目标URI,路由到微服务的地址
           predicates:
               # 匹配对应的URL请求,将匹配到的请求追加在目标 URI 之后
               - Path=/api/product/{segment}
            filters:  # 网关过滤器
                # 将 /api/product/1 重写为 /product/1
                - SetPath=/product/{segment}
SetPath=/product/{segment}

1.2 Parameter参数过滤器

AddRequestParameter 网关过滤器工厂会将指定参数添加至匹配到的下游请求中。

spring:
  application:
    name: gateway-server
  cloud:
    gateway:
      # 路由规则
       routes:
           - id: product-service   # 路由ID,唯一,一般为各个服务名称
           uri: http://localhost:7070/ #目标URI,路由到微服务的地址
           predicates:
               # 匹配对应的URL请求,将匹配到的请求追加在目标 URI 之后
               - Path=/api-gateway/**
            filters:  # 网关过滤器
                # 将 /api-gateway/product/1 重写为 /product/1
                - RewritePath=/api-gateway(?<segment>/?.*), $\{segment}
                # 在下游请求中添加 flag=1
                - AddRequestParameter=flag, 1

1.3 Status 状态过滤器

SetStatus 网关过滤器工厂采用单个状态参数,它必须为是有效的 Spring HttpStatus。它可以是整数404或枚举NOT_FOUND的字符串表示。

spring:
  application:
    name: gateway-server
  cloud:
    gateway:
      # 路由规则
       routes:
           - id: product-service   # 路由ID,唯一,一般为各个服务名称
           uri: http://localhost:7070/ #目标URI,路由到微服务的地址
           predicates:
               # 匹配对应的URL请求,将匹配到的请求追加在目标 URI 之后
               - Path=/api-gateway/**
            filters:  # 网关过滤器
                # 将 /api-gateway/product/1 重写为 /product/1
                - RewritePath=/api-gateway(?<segment>/?.*), $\{segment}
                # 任何情况下,响应的HTTP状态都将设置为404
                - SetStatus=404 # 404 或者对应的枚举 NOT_FOUND
SetStatus=404

2. 自定义过滤器

即使 Spring Cloud Gateway 自带许多实用的 GatewayFilter Factory、Gateway Filter、Global Filter,但是在很多情景下我们仍然希望可以自定义自己的过滤器,实现一些谨慎操作。

2.1 自定义网关过滤器

自定义网关过滤器需要实现以下两个接口:GatewayFilter,Ordered。

public class CustomGatewayFilter implements GatewayFilter, Ordered {
    /**
     * 过滤器业务逻辑
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("自定义网关过滤器被执行");

        return chain.filter(exchange); // 继续向下执行
    }

    /**
     * 过滤器执行顺序,数值越小,优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}

对自定义的过滤器进行注册

@Configuration
public class GatewayRoutesConfiguration {

    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder){
        return builder.routes().route(r -> r
                // 断言(判断条件)
                .path("/product/**")
                // 目标 URI ,路由到微服务的地址
                .uri("http://localhost:7070")
                // 注册自定义网关过滤器
                .filters(new CustomGatewayFilter())
                // 路由 ID, 唯一
                .id("product-service")).build();
    }
}

2.2 自定义全局过滤器

自定义全局过滤器需要实现以下两个接口:GlobalFilter, Ordered。通过全局过滤器可以实现全校校验,安全性验证等功能。

创建过滤器,实现指定接口,添加@component注解即可,一个网关既有网关过滤器又有全局过滤器,则执行顺序,先执行全局过滤器,后执行网关过滤器
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {
    /**
     * 过滤器业务逻辑
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("自定义全局过滤器被执行");
        return chain.filter(exchange); // 继续向下执行
    }

    /**
     * 过滤器执行顺序,数值越小,优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}

2.3 统一鉴权

在网关过滤器中通过token判断用户是否登录,完成一个统一的鉴权案例

@Component
public class AccessFilter implements GlobalFilter, Ordered {
    private Logger logger = (Logger) LoggerFactory.getLogger(AccessFilter.class);

    /**
     *  过滤器业务逻辑
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求参数
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        // 业务逻辑处理
        if(StringUtils.isBlank(token)){
            logger.warning("token is null ...");
            ServerHttpResponse response = exchange.getResponse();
            // 响应类型
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            // 响应状态码,HTTP 401 错误代表用户没有访问权限
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 响应内容
            String message = "{\"message\":\"" + HttpStatus.UNAUTHORIZED.getReasonPhrase() + "\"}";
            DataBuffer buffer = response.bufferFactory().wrap(message.getBytes());
            // 请求结束,不在继续向下请求
            return response.writeWith(Mono.just(buffer));
        }
        // 使用token进行身份验证
        logger.info("token is OK!");
        return chain.filter(exchange);
    }

    /**
     * 过滤器执行顺序,数值越小,优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 1;
    }
}
image.png
image.png

相关文章

网友评论

      本文标题:Gateway网关过滤器

      本文链接:https://www.haomeiwen.com/subject/htppsltx.html