因为我的项目集成了actuator,但是不能将actuator的接口暴露在公网。于是打算写一个拦截器,判断ip是不是内网,但是实现GlobalFilter接口方式 debug根本不进入拦截器。包括添加路由匹配表也不行。

于是想到了springcloud-gateway使用了reactor-netty 就想到了给reactor-netty加拦截器,才成功拦截。

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.http.HttpStatus;

import org.springframework.http.server.reactive.ServerHttpResponse;

import org.springframework.http.server.reactive.ServerHttpRequest;

import org.springframework.web.server.ServerWebExchange;

import org.springframework.web.server.WebFilter;

import reactor.core.publisher.Mono;

@Configuration

public class CustomWebFilterConfig {

@Bean

public WebFilter webFilter() {

return (exchange, chain) -> {

ServerHttpRequest request = exchange.getRequest();

ServerHttpResponse response = exchange.getResponse();

// 获取请求路径

String requestPath = request.getURI().getPath();

String remoteAddress = request.getRemoteAddress().getAddress().getHostAddress();

if (requestPath.startsWith("/actuator")) {

// 如果请求路径以 /actuator 开头,返回 "Access Denied"

response.setStatusCode(HttpStatus.FORBIDDEN);

return response.writeWith(Mono.just(response.bufferFactory().wrap("Access Denied".getBytes())));

} else {

// 否则,继续执行过滤器链

return chain.filter(exchange);

}

};

}

}

文章来源

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。