SpringCloudGateWay自定义自己的GateWayFilterFactory的时候(exchange, chain)

在看SpringCloudGateWay的时候,在实现父类的GatewayFilter apply(C config)方法的时候怎么看也没看明白:

package com.quantex.scg;

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

import java.util.List;


public class WsSecurityGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {

    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return (exchange, chain) -> {
            List<String> strings = exchange.getRequest().getHeaders().get(config.getName());
            if (strings!=null){
                ServerHttpRequest request = exchange.getRequest().mutate()
                        .header(config.getName(), strings.get(0))
                        .build();
//                System.out.println("-----------------------------------------");
//                System.out.println(strings.get(0));
                return chain.filter(exchange.mutate().request(request).build());
            }else{
                return chain.filter(exchange);
            }
        };
    }
}

怎么也没看明白这个函数式的写法(exchange, chain)->{} 不知道到底这exchange和chain是怎么来的,也没看到全局变量啊,我寻思着难道是继承的父类的全局变量?我就一层层找,也灭有找到,实在想不明白,我还以为是容器托管的有名字为exchange和chain的实例,想破脑袋,但是觉得不可能,后来我看了一下apply()这个函数的返回值,是一个GateWayFilter,我就点进去看了一下这个源码如下:

package org.springframework.cloud.gateway.filter;

/*
 * Copyright 2002-2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.springframework.cloud.gateway.support.ShortcutConfigurable;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

/**
 * 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);

}

结果我恍然大悟,这尼玛不是JAVA8的新操作?当接口只有一个没有实现的方法时,如果返回的是一个函数,其实就时返回了这个接口的是一个实现类的实例,对应的实现方法的逻辑就是那个函数,这里的GatewayFilter 的filter方法的实现其实就是:

(exchange, chain) -> {
            List<String> strings = exchange.getRequest().getHeaders().get(config.getName());
            if (strings!=null){
                ServerHttpRequest request = exchange.getRequest().mutate()
                        .header(config.getName(), strings.get(0))
                        .build();
//                System.out.println("-----------------------------------------");
//                System.out.println(strings.get(0));
                return chain.filter(exchange.mutate().request(request).build());
            }else{
                return chain.filter(exchange);
            }
        };

同时(exchange,chain)也刚好对上了接口里的filter的两个参数ServerWebExchange exchange, GatewayFilterChain chain

综上:这个其实就是JAVA8的函数式接口, 知道java8的特性,但是操作的少。才会出现这种知道但是看不懂的情况,其实函数式接口很简单,下面的链接3分钟就能看明白.

JAVA8特性之函数式接口-@FunctionalInterface注解https://blog.csdn.net/qq_15022971/article/details/126176275?spm=1001.2014.3001.5501

  • 5
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
好的,下面是一个简单的自定义过滤器的代码示例: 1. 创建自定义过滤器类 ```java import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.core.Ordered; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; @Component public class CustomGatewayFilter implements GatewayFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { // 自定义过滤器逻辑 System.out.println("Custom Gateway Filter executed!"); return chain.filter(exchange); } @Override public int getOrder() { return -1; // 设置过滤器执行顺序 } } ``` 2. 创建自定义过滤器工厂类 ```java import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; import org.springframework.stereotype.Component; @Component public class CustomGatewayFilterFactory extends AbstractGatewayFilterFactory<CustomGatewayFilterFactory.Config> { public CustomGatewayFilterFactory() { super(Config.class); } @Override public GatewayFilter apply(Config config) { return new CustomGatewayFilter(); } public static class Config { // 可以在这里添加自定义配置项 } } ``` 3. 配置自定义过滤器 在Spring Boot应用程序中的配置文件(如application.yml)中添加以下配置: ```yaml spring: cloud: gateway: routes: - id: my_route uri: http://localhost:8080 predicates: - Path=/foo/** filters: - CustomGatewayFilter ``` 或者在Java代码中使用以下方式配置: ```java @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { return builder.routes() .route("my_route", r -> r.path("/foo/**") .filters(f -> f.filter(new CustomGatewayFilter())) .uri("http://localhost:8080")) .build(); } ``` 以上代码示例中,我们创建了一个名为“CustomGatewayFilter”的自定义过滤器,该过滤器在执行时会打印一条日志。我们还创建了一个名为“CustomGatewayFilterFactory”的自定义过滤器工厂类,这个工厂类会返回一个自定义过滤器实例。最后,我们在Spring Cloud Gateway的配置中使用了这个自定义过滤器。 希望这个示例对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值