Spring Cloud——GateWay网关Filter的使用

是什么

路由过滤器可用于修改进入的HTTP请求和返回的HTTP响应,路由过滤器只能指定路由进行使用。 Spring Cloud Gateway 内置了多种路由过滤器,他们都由GatewayFilter的工厂类来产生

Gateway自带的Filter种类繁多,具体可以参见官网

自定义过滤器 

自定义全局GlobalFilter

定义一个Filter类注入spring容器

实现GlobalFilter,Ordered 这两个接口

package com.atguigu.springcloud.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.filter.OrderedFilter;
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.Date;

/**
 * <p>
 * 自定义GateWay过滤器
 * </P>
 *
 * @author Kk
 * @since 2022/4/14 21:24
 */
@Component
@Slf4j
public class MyLogGateWayFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("time:"+new Date()+"	 执行了自定义的全局过滤器: "+"MyLogGateWayFilter"+"hello");
        //拦截请求路径中的查询参数
        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
        //如果没有uname,将会被拦截访问不了
        if (uname == null) {
            log.info("**************非法用户,禁止访问");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    /*
    全局过滤器优先级设置为最高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}

能干嘛

    全局日志记录 统一网关鉴权 。。。。。。

测试

正确路径:

2022-04-16 15:48:22.593  INFO 14804 --- [ctor-http-nio-6] c.a.s.filter.MyLogGateWayFilter          : time:Sat Apr 16 15:48:22 CST 2022	 执行了自定义的全局过滤器: MyLogGateWayFilterhello
2022-04-16 15:48:22.748  INFO 14804 --- [ctor-http-nio-6] c.a.s.filter.MyLogGateWayFilter          : time:Sat Apr 16 15:48:22 CST 2022	 执行了自定义的全局过滤器: MyLogGateWayFilterhello
2022-04-16 15:49:27.156  INFO 14804 --- [ctor-http-nio-1] c.a.s.filter.MyLogGateWayFilter          : time:Sat Apr 16 15:49:27 CST 2022	 执行了自定义的全局过滤器: MyLogGateWayFilterhello

错误路径(没有参数uname):

2022-04-16 15:49:27.156  INFO 14804 --- [ctor-http-nio-1] c.a.s.filter.MyLogGateWayFilter          : **************非法用户,禁止访问
2022-04-16 15:49:43.423  INFO 14804 --- [ctor-http-nio-6] c.a.s.filter.MyLogGateWayFilter          : time:Sat Apr 16 15:49:43 CST 2022	 执行了自定义的全局过滤器: MyLogGateWayFilterhello
2022-04-16 15:49:43.423  INFO 14804 --- [ctor-http-nio-6] c.a.s.filter.MyLogGateWayFilter          : **************非法用户,禁止访问

请求被拦截,无法访问

经验分享 程序员 微信小程序 职场和发展