2018-05-21 · 许进 · · 字数:491·阅读时间 1 分钟 阅读量

摘要:Spring Cloud Gateway只有两种类型的Filter,本文介绍如何在Spring Cloud Gateway中创建一个Pre或Post类型的Filter。

zuul的Filter类型

Zuul 的 Filter 是通过filterType()方法来指定,一个 Filter 只能对应一种类型,要么是 “pre” 要么是“post”

Spring Cloud Gateway的Filter类型

Spring Cloud Gateway 基于 Project Reactor 和 WebFlux,采用响应式编程风格,打开它的 Filter 的接口GatewayFilter你会发现它只有一个方法filter

Pre类型的Filter

在Spring Cloud Gateway源码中定义了一个Pre类型的Filter,code将会在chain.filter() 之前被执行,代码:AddRequestHeader

package org.springframework.cloud.gateway.filter.factory;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;

/**
 * @author Spencer Gibb
 */
public class AddRequestHeaderGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {

    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest().mutate()
                    .header(config.getName(), config.getValue())
                    .build();

            return chain.filter(exchange.mutate().request(request).build());
        };
    }

}

Post类型的Filter

对于Post类型的Filter,SetStatus 代码将会在chain.filter(exchange).then()里面的代码运行。

public class SetStatusGatewayFilterFactory extends AbstractGatewayFilterFactory<SetStatusGatewayFilterFactory.Config> {
    @Override
    public GatewayFilter apply(Config config) {
        final HttpStatus status = ServerWebExchangeUtils.parse(config.status);
        return (exchange, chain) -> {

            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                // check not really needed, since it is guarded in setStatusCode,
                // but it's a good example
                if (!exchange.getResponse().isCommitted()) {
                    setResponseStatus(exchange, status);
                }
            }));
        };
    }
}