使用getway网关过滤器只需要在filter包里面的类中继承GlobalFilter 和 Ordered即可
示范代码:
package com.changgou.filter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.net.InetAddress;
import java.net.InetSocketAddress;
@Component
public class IpFilter implements GlobalFilter, Ordered {
private static Log log = LogFactory.getLog(IpFilter.class);
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
InetSocketAddress remoteAddress = request.getRemoteAddress();
System.out.println(remoteAddress.getAddress());
System.out.println(remoteAddress.getHostName());
System.out.println(remoteAddress.getHostString());
System.out.println(remoteAddress.getPort());
String path = request.getURI().getPath();
System.out.println(path);
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
}
其中getorder的返回值代表过滤器的执行顺序,值越小越先执行
如果要对请求进行拦截直接return null;即可,放行直接return chain.filter(exchange)即可,非常的方便