当前位置: 欣欣网 > 码农

今日代码大赏 | Spring Cloud Gateway 全局过滤器实现

2024-05-11码农

在构建微服务架构时,Spring Cloud Gateway 作为服务网关,承担着路由转发、权限校验等职责。

全局过滤器(Global Filter)是 Spring Cloud Gateway 中用于处理跨服务的通用逻辑的组件,例如权限验证、日志记录等。

下面是Spring Cloud Gateway中实现全局过滤器的示例代码:

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
@Component
public classGlobalAuthFilterimplementsGlobalFilter, Ordered {
privateAntPathMatcherantPathMatcher = newAntPathMatcher();
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequestserverHttpRequest = exchange.getRequest();
Stringpath = serverHttpRequest.getURI().getPath();
// 判断路径中是否包含 "inner",只允许内部调用
if (antPathMatcher.match("/**/inner/**", path)) {
ServerHttpResponseresponse = exchange.getResponse();
response.setStatusCode(HttpStatus.FORBIDDEN);
DataBufferFactorydataBufferFactory = response.bufferFactory();
DataBufferdataBuffer = dataBufferFactory.wrap("无权限".getBytes(StandardCharsets.UTF_8));
return response.writeWith(Mono.just(dataBuffer));
}
// 统一权限校验,此处应添加JWT等验证逻辑
// todo 统一权限校验,通过 JWT 获取登录用户信息
return chain.filter(exchange);
}
/**
* 设置过滤器的优先级
* 值越小,优先级越高
@return
*/

@Override
publicintgetOrder() {
return0;
}
}




全局过滤器的优点

  • 统一处理 :可以在一个地方集中处理所有请求的预处理和后处理逻辑。

  • 顺序可控 :通过实现 Ordered 接口,可以控制过滤器的执行顺序。

  • 今天的代码大赏就到这里。希望通过这篇文章,你能够对 Spring Cloud Gateway 全局过滤器 实现有一个更深入的理解。

    完整代码片段 来源于代码小抄,欢迎点击进入小程序阅读!

    在线访问:https://www.codecopy.cn/post/kt2g78

    在代码小抄可以看到更多优质代码,也欢迎大家积极分享,可能会获得我们官方的小礼品 🎁~

    往期推荐