站长之家官网查询,网站建设图书推荐,上海房产网签,centos 下载wordpress文章目录 1. 网关的过滤器清单2. GatewayFilterFactory和GlobalFilter 的原理3. RuoYi网关的配置文件是如何配置的4. 资料参考 本文主要介绍 RuoYi 中用到的过滤器#xff0c;以及过滤器原理简单分析。Spring Gateway 的详细原理请参考作者另外的文章。 1. 网关的过滤器清单
… 文章目录 1. 网关的过滤器清单2. GatewayFilterFactory和GlobalFilter 的原理3. RuoYi网关的配置文件是如何配置的4. 资料参考 本文主要介绍 RuoYi 中用到的过滤器以及过滤器原理简单分析。Spring Gateway 的详细原理请参考作者另外的文章。 1. 网关的过滤器清单
在“网关模块”一共定义了5个过滤器。分类如下
继承AbstractGatewayFilterFactory的 ValidateCodeFilter(验证码过滤器)BlackListUrlFilter(黑名单过滤器)CacheRequestFilter 实现GlobalFilter, Ordered接口 XssFilter(跨站脚本过滤器)AuthFilter(网关鉴权)
2. GatewayFilterFactory和GlobalFilter 的原理
有以下几个问题需要解决
继承 AbstractGatewayFilterFactory 类和实现 GlobalFilter, Ordered 接口 2 种方式的过滤器有什么不同 GlobalFilter 参考https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#gateway-combined-global-filter-and-gatewayfilter-ordering GatewayFilterFactory参考https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#gatewayfilter-factories 关键是GlobalFilter 针对“所有路由”而 GatewayFilterFactory 针对“特定路由” 为什么实现 Spring 的 Ordered 接口
为了控制过滤器的顺序Spring 的 Ordered 接口是根据 order 值升序排序的。
既有继承又有实现接口它们的顺序是怎么样的
public MonoVoid handle(ServerWebExchange exchange) {Route route exchange.getRequiredAttribute(GATEWAY_ROUTE_ATTR);ListGatewayFilter gatewayFilters route.getFilters();ListGatewayFilter combined new ArrayList(this.globalFilters);combined.addAll(gatewayFilters);// TODO: needed or cached?AnnotationAwareOrderComparator.sort(combined);if (logger.isDebugEnabled()) {logger.debug(Sorted gatewayFilterFactories: combined);}return new DefaultGatewayFilterChain(combined).filter(exchange);
}从以上 combine 可以看到先从请求 request 属性中获取了特定路由的过滤器gatewayFilters在结合全局过滤器combined最后经过 Ordered 排序。但是继承GatewayFilterFactory并没有指定 order 的值只有实现 Ordered 接口才指定了 order 值此时怎么处理GatewayFilterFactory的??? 猜测是不是跟 nacos 的网关 route 配置的 filters 的顺序有关呢。
3. RuoYi网关的配置文件是如何配置的
在 nacos 的网关配置文件 ruoyi-gateway-dev.yml 中给 ruoyi-auth 模块多配置了几个过滤器 filter。
spring:redis:host: localhostport: 6379password:cloud:gateway:discovery:locator:lowerCaseServiceId: trueenabled: trueroutes:# 认证中心- id: ruoyi-authuri: lb://ruoyi-authpredicates:- Path/auth/**filters:# 验证码处理- CacheRequestFilter- ValidateCodeFilter- StripPrefix1# 代码生成- id: ruoyi-genuri: lb://ruoyi-genpredicates:- Path/code/**filters:- StripPrefix1# 定时任务- id: ruoyi-joburi: lb://ruoyi-jobpredicates:- Path/schedule/**filters:- StripPrefix1# 系统模块- id: ruoyi-systemuri: lb://ruoyi-systempredicates:- Path/system/**filters:- StripPrefix1# 文件服务- id: ruoyi-fileuri: lb://ruoyi-filepredicates:- Path/file/**filters:- StripPrefix1# 安全配置
security:# 验证码captcha:enabled: truetype: math# 防止XSS攻击xss:enabled: trueexcludeUrls:- /system/notice# 不校验白名单ignore:whites:- /auth/logout- /auth/login- /auth/register- /*/v2/api-docs- /csrf
其中给Auth模块特别配置了CacheRequestFilter、ValidateCodeFilter。其它模块全局使用了XssFilter、AuthFilter过滤器
4. 资料参考
语雀笔记地址https://www.yuque.com/yuchangyuan/tkb5br