ITPub博客

首页 > 数据库 > 数据库开发技术 > 今日代码大赏 | Spring Cloud Gateway 全局过滤器实现

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

原创 数据库开发技术 作者:程序员鱼皮 时间:2024-05-11 17:28:27 0 删除 编辑

在构建微服务架构时,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 class GlobalAuthFilter implements GlobalFilter, Ordered {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        String path = serverHttpRequest.getURI().getPath();
        // 判断路径中是否包含 "inner",只允许内部调用
        if (antPathMatcher.match("/**/inner/**", path)) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.FORBIDDEN);
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            DataBuffer dataBuffer = dataBufferFactory.wrap("无权限".getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }
        // 统一权限校验,此处应添加JWT等验证逻辑
        // todo 统一权限校验,通过 JWT 获取登录用户信息
        return chain.filter(exchange);
    }

    /**
     * 设置过滤器的优先级
     * 值越小,优先级越高
     * @return
     */

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

全局过滤器的优点

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

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

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

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

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

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

往期推荐

今日代码大赏 | Java 序列化

今日代码大赏 | 工厂方法模式

今日代码大赏 | Git 常用命令

今日代码大赏 | Spring Boot 健康检查接口

今日代码大赏 | Java 获取客户端 IP 地址

原文作者:程序员鱼皮;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2023-12-20

  • 博文量
    330
  • 访问量
    151640