spring cloud gateway 全局过滤器

全局过滤器做用于全部的路由,不须要单独配置,咱们能够用它来实现不少统一化处理的业务需求,好比权限认证,IP访问限制等等。spring

接口定义类:org.springframework.cloud.gateway.filter.GlobalFilterjson

public interface GlobalFilter {
    Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain);
}

gateway自带的GlobalFilter实现类有不少,以下图:微信

GlobalFilter实现类

有转发,路由,负载等相关的GlobalFilter,感兴趣的能够本身去看下源码,了解下。app

咱们本身如何定义GlobalFilter来实现咱们本身的业务逻辑?ide

给出一个官方文档上的案例:oop

@Configuration
public class ExampleConfiguration {
    private Logger log = LoggerFactory.getLogger(ExampleConfiguration.class);

    @Bean
    @Order(-1)
    public GlobalFilter a() {
        return (exchange, chain) -> {
            log.info("first pre filter");
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                log.info("third post filter");
            }));
        };
    }

    @Bean
    @Order(0)
    public GlobalFilter b() {
        return (exchange, chain) -> {
            log.info("second pre filter");
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                log.info("second post filter");
            }));
        };
    }

    @Bean
    @Order(1)
    public GlobalFilter c() {
        return (exchange, chain) -> {
            log.info("third pre filter");
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                log.info("first post filter");
            }));
        };
    }
}

上面定义了3个GlobalFilter,经过@Order来指定执行的顺序,数字越小,优先级越高。下面就是输出的日志,从日志就能够看出执行的顺序:post

2018-10-14 12:08:52.406  INFO 55062 --- [ioEventLoop-4-1] c.c.gateway.config.ExampleConfiguration  : first pre filter
2018-10-14 12:08:52.406  INFO 55062 --- [ioEventLoop-4-1] c.c.gateway.config.ExampleConfiguration  : second pre filter
2018-10-14 12:08:52.407  INFO 55062 --- [ioEventLoop-4-1] c.c.gateway.config.ExampleConfiguration  : third pre filter
2018-10-14 12:08:52.437  INFO 55062 --- [ctor-http-nio-7] c.c.gateway.config.ExampleConfiguration  : first post filter
2018-10-14 12:08:52.438  INFO 55062 --- [ctor-http-nio-7] c.c.gateway.config.ExampleConfiguration  : second post filter
2018-10-14 12:08:52.438  INFO 55062 --- [ctor-http-nio-7] c.c.gateway.config.ExampleConfiguration  : third post filter

当GlobalFilter的逻辑比较多时,我仍是推荐你们单独写一个GlobalFilter来处理,好比咱们要实现对IP的访问限制,不在IP白名单中就不让调用的需求。学习

单独定义只须要实现GlobalFilter, Ordered这两个接口就能够了。测试

@Component
public class IPCheckFilter implements GlobalFilter, Ordered {

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        HttpHeaders headers = exchange.getRequest().getHeaders();
        // 此处写死了,演示用,实际中须要采起配置的方式
        if (getIp(headers).equals("127.0.0.1")) {
            ServerHttpResponse response = exchange.getResponse();
            ResponseData data = new ResponseData();
            data.setCode(401);
            data.setMessage("非法请求");
            byte[] datas = JsonUtils.toJson(data).getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(datas);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }
        return chain.filter(exchange);
    }

    // 这边从请求头中获取用户的实际IP,根据Nginx转发的请求头获取
    private String getIp(HttpHeaders headers) {
        return "127.0.0.1";
    }

}

过滤的使用没什么好讲的,都比较简单,做用却很大,能够处理不少需求,上面讲的IP认证拦截只是冰山一角,更多的功能须要咱们本身基于过滤器去实现。ui

好比我想作a/b测试,那么就得在路由转发层面作文章,前面咱们有贴一个图片,图片中有不少默认的全局过滤器,其中有一个LoadBalancerClientFilter是负责选择路由服务的负载过滤器,里面会经过loadBalancer去选择转发的服务,而后传递到下面的路由NettyRoutingFilter过滤器去执行,那么咱们就能够基于这个机制来实现。

Filter中往下一个Filter中传递数据实用下面的方式:

exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, requestUrl);

获取方直接获取:

URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);

若是我想改变路由的话,就能够这样作:

@Component
public class DebugFilter implements GlobalFilter, Ordered {

    @Override
    public int getOrder() {
        return 10101;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, new URI("http://192.168.31.245:8081/house/hello2"));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return chain.filter(exchange);
    }

}

LoadBalancerClientFilter的order是10100,咱们这边比它大1,这样就能在它执行完以后来替换要路由的地址了。

欢迎加入个人知识星球,一块儿交流技术,免费学习猿天地的课程(http://cxytiandi.com/course

微信扫码加入猿天地知识星球

猿天地

相关文章
相关标签/搜索