spring cloud gateway过滤器及执行顺序

本文深入解析Spring Cloud Gateway的过滤器机制,包括GatewayFilter、GlobalFilter、GatewayFilterChain的作用及生命周期,以及如何通过配置文件生成过滤器。

一、图谱

在Spring-Cloud-Gateway之请求处理流程中最终网关是将请求交给过滤器链表进行处理。
核心接口:GatewayFilter(网关过滤器),GlobalFilter(全局过滤器),GatewayFilterChain(过滤器链)。
类关联图:
关联

二、为什么使用网关过滤器

现在流行的微服务,整个项目包含很多个服务,如果没有网关这层,那么我们通过什么方式来限制访问呢?难道在每个服务都建立一套验证,这样代码就看的非常冗余,因此网关的出现解决了这点,只需要在gateway上建立一套验证就可以对整个服务进行使用。感觉有点像计算机网络中的7层协议一样。

三、Filter

生命周期

Spring Cloud Gateway 的 Filter 的生命周期有两个:“pre” 和 “post”。
“pre”:请求被执行前调用
“post”:被执行后调用

接口分析

3.1、GatewayFilter–网关路由过滤器
源码:

/**
 * 网关路由过滤器,
 * Contract for interception-style, chained processing of Web requests that may
 * be used to implement cross-cutting, application-agnostic requirements such
 * as security, timeouts, and others. Specific to a Gateway
 *
 */
public interface GatewayFilter extends ShortcutConfigurable {

    String NAME_KEY = "name";
    String VALUE_KEY = "value";

    /**
     *  过滤器执行方法
     * Process the Web request and (optionally) delegate to the next
     * {@code WebFilter} through the given {@link GatewayFilterChain}.
     * @param exchange the current server exchange
     * @param chain provides a way to delegate to the next filter
     * @return {@code Mono<Void>} to indicate when request processing is complete
     */
    Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain);

}

网关过滤器接口,有且只有一个方法filter,执行当前过滤器,并在此方法中决定过滤器链表是否继续往下执行。
我们讲解两个实现GatewayFilter的类
3.1.1、OrderedGatewayFilter–排序
源码:

/**
 * 排序的网关路由过滤器,用于包装真实的网关过滤器,已达到过滤器可排序
 */
public class OrderedGatewayFilter implements GatewayFilter, Ordered {

    //目标过滤器
    private final GatewayFilter delegate;
    //排序字段
    private final int order;

    public OrderedGatewayFilter(GatewayFilter delegate, int order) {
        this.delegate = delegate;
        this.order = order;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return this.delegate.filter(exchange, chain);
    }
}

OrderedGatewayFilter实现类主要目的是为了将目标过滤器包装成可排序的对象类型。是目标过滤器的包装类
3.1.2、GatewayFilterAdapter–适配器
源码:

/**
     * 全局过滤器的包装类,将全局路由包装成统一的网关过滤器
     */
    private static class GatewayFilterAdapter implements GatewayFilter {

        /**
         * 全局过滤器
         */
        private final GlobalFilter delegate;

        public GatewayFilterAdapter(GlobalFilter delegate) {
            this.delegate = delegate;
        }

        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            return this.delegate.filter(exchange, chain);
        }
    }
</
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值