聊聊spring cloud gateway的GatewayFilter

本文主要研究一下spring cloud gateway的GatewayFilter

GatewayFilter

spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/filter/GatewayFilter.java

/**
 * 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
 *
 * Copied from WebFilter
 *
 * @author Rossen Stoyanchev
 * @since 5.0
 */
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);

}

如注释所说,主要用于类似切面的非功能性需求,比如安全、超时控制等。其直接的实现类为OrderedGatewayFilter、ModifyResponseGatewayFilter、GatewayFilterAdapter

OrderedGatewayFilter

spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/filter/OrderedGatewayFilter.java

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;
    }

    public GatewayFilter getDelegate() {
        return delegate;
    }

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

    @Override
    public int getOrder() {
        return this.order;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("OrderedGatewayFilter{");
        sb.append("delegate=").append(delegate);
        sb.append(", order=").append(order);
        sb.append('}');
        return sb.toString();
    }
}

实现了Order接口

ModifyResponseGatewayFilter

spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/filter/factory/rewrite/ModifyResponseBodyGatewayFilterFactory.java

    public class ModifyResponseGatewayFilter implements GatewayFilter, Ordered {
        private final Config config;

        public ModifyResponseGatewayFilter(Config config) {
            this.config = config;
        }

        @Override
        @SuppressWarnings("unchecked")
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            ServerHttpResponseDecorator responseDecorator = new ServerHttpResponseDecorator(exchange.getResponse()) {
                @Override
                public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {

                    ResolvableType inElementType = ResolvableType.forClass(config.getInClass());
                    ResolvableType outElementType = ResolvableType.forClass(config.getOutClass());
                    MediaType contentType = exchange.getResponse().getHeaders().getContentType();
                    Optional<HttpMessageReader<?>> reader = getHttpMessageReader(codecConfigurer, inElementType, contentType);
                    Optional<HttpMessageWriter<?>> writer = getHttpMessageWriter(codecConfigurer, outElementType, null);

                    if (reader.isPresent() && writer.isPresent()) {

                        ResponseAdapter responseAdapter = new ResponseAdapter(body, getDelegate().getHeaders());

                        Flux<?> modified = reader.get().read(inElementType, responseAdapter, config.getInHints())
                                .cast(inElementType.resolve())
                                .flatMap(originalBody -> Flux.just(config.rewriteFunction.apply(exchange, originalBody)))
                                .cast(outElementType.resolve());

                        return getDelegate().writeWith(
                                writer.get().write((Publisher)modified, outElementType, null, getDelegate(),
                                        config.getOutHints())
                        );

                    }
                    // TODO: error? log?

                    return getDelegate().writeWith(body);
                }

                @Override
                public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) {
                    return writeWith(Flux.from(body)
                            .flatMapSequential(p -> p));
                }
            };

            return chain.filter(exchange.mutate().response(responseDecorator).build());
        }

        @Override
        public int getOrder() {
            return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 1;
        }

    }

主要用于修改response

GatewayFilterAdapter

spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/handler/FilteringWebHandler.java

    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);
        }

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("GatewayFilterAdapter{");
            sb.append("delegate=").append(delegate);
            sb.append('}');
            return sb.toString();
        }
    }

将GlobalFilter转为GatewayFilter的适配器

GatewayFilterFactory

spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/filter/factory/GatewayFilterFactory.java

@FunctionalInterface
public interface GatewayFilterFactory<C> extends ShortcutConfigurable, Configurable<C> {

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

    // useful for javadsl
    default GatewayFilter apply(Consumer<C> consumer) {
        C config = newConfig();
        consumer.accept(config);
        return apply(config);
    }

    default Class<C> getConfigClass() {
        throw new UnsupportedOperationException("getConfigClass() not implemented");
    }

    @Override
    default C newConfig() {
        throw new UnsupportedOperationException("newConfig() not implemented");
    }

    GatewayFilter apply(C config);

    default String name() {
        //TODO: deal with proxys
        return NameUtils.normalizeFilterFactoryName(getClass());
    }

    @Deprecated
    default ServerHttpRequest.Builder mutate(ServerHttpRequest request) {
        return request.mutate();
    }
}

spring cloud gateway采用工厂模式来生成GatewayFilter,可以看到这里定义了apply方法,根据config来生成GatewayFilter。GatewayFilterFactory有几个抽象类,分别是AbstractGatewayFilterFactory、AbstractNameValueGatewayFilterFactory(继承了AbstractGatewayFilterFactory)、AbstractChangeRequestUriGatewayFilterFactory。

AbstractGatewayFilterFactory

spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/filter/factory/AbstractGatewayFilterFactory.java

public abstract class AbstractGatewayFilterFactory<C>
        extends AbstractConfigurable<C> implements GatewayFilterFactory<C> {

    @SuppressWarnings("unchecked")
    public AbstractGatewayFilterFactory() {
        super((Class<C>) Object.class);
    }

    public AbstractGatewayFilterFactory(Class<C> configClass) {
        super(configClass);
    }

    public static class NameConfig {
        private String name;

        public String getName() {
            return name;
        }

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

它的直接实现类如下:

  • HystrixGatewayFilterFactory
  • ModifyRequestBodyGatewayFilterFactory
  • ModifyResponseBodyGatewayFilterFactory
  • PrefixPathGatewayFilterFactory
  • PreserveHostHeaderGatewayFilterFactory
  • RedirectToGatewayFilterFactory
  • RemoveRequestHeaderGatewayFilterFactory
  • RemoveResponseHeaderGatewayFilterFactory
  • RequestRateLimiterGatewayFilterFactory
  • RetryGatewayFilterFactory
  • RewritePathGatewayFilterFactory
  • SaveSessionGatewayFilterFactory
  • SecureHeadersGatewayFilterFactory
  • SetPathGatewayFilterFactory
  • SetStatusGatewayFilterFactory
  • StripPrefixGatewayFilterFactory

AbstractNameValueGatewayFilterFactory

spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/filter/factory/AbstractNameValueGatewayFilterFactory.java

public abstract class AbstractNameValueGatewayFilterFactory extends AbstractGatewayFilterFactory<AbstractNameValueGatewayFilterFactory.NameValueConfig> {

    public AbstractNameValueGatewayFilterFactory() {
        super(NameValueConfig.class);
    }

    public List<String> shortcutFieldOrder() {
        return Arrays.asList(GatewayFilter.NAME_KEY, GatewayFilter.VALUE_KEY);
    }


    @Validated
    public static class NameValueConfig {
        @NotEmpty
        protected String name;
        @NotEmpty
        protected String value;

        public String getName() {
            return name;
        }

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

        public String getValue() {
            return value;
        }

        public NameValueConfig setValue(String value) {
            this.value = value;
            return this;
        }

        @Override
        public String toString() {
            return new ToStringCreator(this)
                    .append("name", name)
                    .append("value", value)
                    .toString();
        }
    }
}

将泛型限定为AbstractNameValueGatewayFilterFactory.NameValueConfig,其实现类如下:

  • AddRequestHeaderGatewayFilterFactory
  • AddRequestParameterGatewayFilterFactory
  • AddResponseHeaderGatewayFilterFactory
  • SetRequestHeaderGatewayFilterFactory
  • SetResponseHeaderGatewayFilterFactory

AbstractChangeRequestUriGatewayFilterFactory

spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/filter/factory/AbstractChangeRequestUriGatewayFilterFactory.java

/**
 * This filter changes the request uri by
 * {@link #determineRequestUri(ServerWebExchange, T)} logic.
 *
 * @author Toshiaki Maki
 */
public abstract class AbstractChangeRequestUriGatewayFilterFactory<T>
        extends AbstractGatewayFilterFactory<T> {
    private final int order;

    public AbstractChangeRequestUriGatewayFilterFactory(Class<T> clazz, int order) {
        super(clazz);
        this.order = order;
    }

    public AbstractChangeRequestUriGatewayFilterFactory(Class<T> clazz) {
        this(clazz, RouteToRequestUrlFilter.ROUTE_TO_URL_FILTER_ORDER + 1);
    }

    protected abstract Optional<URI> determineRequestUri(ServerWebExchange exchange,
            T config);

    public GatewayFilter apply(T config) {
        return new OrderedGatewayFilter((exchange, chain) -> {
            Optional<URI> uri = this.determineRequestUri(exchange, config);
            uri.ifPresent(u -> {
                Map<String, Object> attributes = exchange.getAttributes();
                attributes.put(GATEWAY_REQUEST_URL_ATTR, u);
            });
            return chain.filter(exchange);
        }, this.order);
    }
}

通过GATEWAY_REQUEST_URL_ATTR设置新的uri,其直接实现类为

  • RequestHeaderToRequestUriGatewayFilterFactory(通过header的值来设定uri)

GatewayFilterFactory.apply

spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/route/RouteDefinitionRouteLocator.java

    private List<GatewayFilter> loadGatewayFilters(String id, List<FilterDefinition> filterDefinitions) {
        List<GatewayFilter> filters = filterDefinitions.stream()
                .map(definition -> {
                    GatewayFilterFactory factory = this.gatewayFilterFactories.get(definition.getName());
                    if (factory == null) {
                        throw new IllegalArgumentException("Unable to find GatewayFilterFactory with name " + definition.getName());
                    }
                    Map<String, String> args = definition.getArgs();
                    if (logger.isDebugEnabled()) {
                        logger.debug("RouteDefinition " + id + " applying filter " + args + " to " + definition.getName());
                    }

                    Map<String, Object> properties = factory.shortcutType().normalize(args, factory, this.parser, this.beanFactory);

                    Object configuration = factory.newConfig();

                    ConfigurationUtils.bind(configuration, properties,
                            factory.shortcutFieldPrefix(), definition.getName(), validator);

                    GatewayFilter gatewayFilter = factory.apply(configuration);
                    if (this.publisher != null) {
                        this.publisher.publishEvent(new FilterArgsEvent(this, id, properties));
                    }
                    return gatewayFilter;
                })
                .collect(Collectors.toList());

        ArrayList<GatewayFilter> ordered = new ArrayList<>(filters.size());
        for (int i = 0; i < filters.size(); i++) {
            GatewayFilter gatewayFilter = filters.get(i);
            if (gatewayFilter instanceof Ordered) {
                ordered.add(gatewayFilter);
            }
            else {
                ordered.add(new OrderedGatewayFilter(gatewayFilter, i + 1));
            }
        }

        return ordered;
    }

这里通过factory去实例化每个route的GatewayFilter

小结

spring cloud gateway的GatewayFilter主要是通过GatewayFilterFactory来生产的。而GatewayFilterFactory主要有三个抽象类:

  • AbstractGatewayFilterFactory
    • HystrixGatewayFilterFactory
    • ModifyRequestBodyGatewayFilterFactory
    • ModifyResponseBodyGatewayFilterFactory
    • PrefixPathGatewayFilterFactory
    • PreserveHostHeaderGatewayFilterFactory
    • RedirectToGatewayFilterFactory
    • RemoveRequestHeaderGatewayFilterFactory
    • RemoveResponseHeaderGatewayFilterFactory
    • RequestRateLimiterGatewayFilterFactory
    • RetryGatewayFilterFactory
    • RewritePathGatewayFilterFactory
    • SaveSessionGatewayFilterFactory
    • SecureHeadersGatewayFilterFactory
    • SetPathGatewayFilterFactory
    • SetStatusGatewayFilterFactory
    • StripPrefixGatewayFilterFactory
  • AbstractNameValueGatewayFilterFactory(继承了AbstractGatewayFilterFactory)
    • AddRequestHeaderGatewayFilterFactory
    • AddRequestParameterGatewayFilterFactory
    • AddResponseHeaderGatewayFilterFactory
    • SetRequestHeaderGatewayFilterFactory
    • SetResponseHeaderGatewayFilterFactory
  • AbstractChangeRequestUriGatewayFilterFactory
    • RequestHeaderToRequestUriGatewayFilterFactory

doc

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,033评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,725评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,473评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,846评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,848评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,691评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,053评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,700评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,856评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,676评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,787评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,430评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,034评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,990评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,218评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,174评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,526评论 2 343

推荐阅读更多精彩内容