Solon Cloud Gateway 补充

说明

在「使用 Solon Cloud Gateway 替换Spring Cloud Gateway 」的文章中,有评论说不知道响应式。当时看的是

Solon Cloud Gateway 使用响应式接口,由 Solon-Rx 来实现,是基于 reactive-streams 封装的 RxJava 极简版。目前仅一个接口 Completable,所以当时以为实现了 ExFilter 返回 Completable 就是响应式了。后续 Solon Cloud Gateway 继续更新文档之后才发现,虽然网关是响应式了,但如果逻辑涉及 IO 或者比较慢的操作,需要在 ExFilter 中开启异步接口,这样才是真正的异步,从而避免对网关的事件循环器造成影响,减少对响应式的性能的伤害。

为了对接同步 IO 接口,Solon 3.2.1 提供了 CloudGatewayFilterSync,用于简化异步调用的编写。

基础版

java 复制代码
//同步过滤器(会自动转异步)
@FunctionalInterfacepublic interface ExFilterSync extends ExFilter {
    @Overridedefault Completable doFilter(ExContext ctx, ExFilterChain chain) {
        return Completable.create(emitter -> {
            //暂停接收流
            ctx.pause();

            //开始异步
            RunUtil.async(() -> {
                try {
                    //开始同步处理boolean isContinue = doFilterSync(ctx);

                    if (isContinue) {
                        //继续
                        chain.doFilter(ctx).subscribe(emitter);
                    } else {
                        //结束
                        emitter.onComplete();
                    }
                } catch (Throwable ex) {
                    emitter.onError(ex);
                }
            });
        });
    }

    /**
     * 执行过滤同步处理(一般用于同步 io)
     *
     * @param ctx 上下文
     * @return 是否继续
     */boolean doFilterSync(ExContext ctx) throws Throwable;
}

这个 doFilter 的过程中需要自己先处理 ctx.pause,然后开启异步,并在开启的过程中判断是否异常的提交等等,需要写好这个 ExFitler 的扩展还是有点不容易的。

于是作者又贴心的提供了CloudGatewayFilterSync

简化版

java 复制代码
@Component(index = -9)
public class AuthFilterSync implements CloudGatewayFilterSync {
    @Inject
    AuthJdbcService authService;

    @Overridepublic boolean doFilterSync(ExContext ctx) throws Throwable {
        String userId = ctx.rawQueryParam("userId");
        //检测路径权限
        return authService.check(userId, ctx.rawPath());
    }
}

在简化的版本中,只需要在 doFilterSync 中编写具体的逻辑,而不要关心流的暂停和开启异步等。如果已经处理完毕,不需要继续执行返回 ture,否则返回 false。

参考

https://solon.noear.org/article/813

https://solon.noear.org/article/1005

相关推荐
亚林瓜子1 天前
AWS中国区中API Gateway中403的AccessDeniedException问题
云计算·gateway·api·aws
blammmp3 天前
Spring Cloud:Gateway(统一服务入口)
spring·spring cloud·gateway
Nerd Nirvana4 天前
网关GateWay——连接不同网络的关键设备
网络·mqtt·计算机网络·gateway·路由器·modbus·电力设备
Paran-ia4 天前
【2025版】SpringCloud Gateway网关快速入门
spring·spring cloud·gateway
泽济天下6 天前
【工作记录】Kong Gateway入门篇之简介
gateway·kong
SHUIPING_YANG6 天前
Nginx 返回 504 状态码表示 网关超时(Gateway Timeout)原因排查
运维·nginx·gateway
Volunteer Technology7 天前
SpringCloud Gateway知识点整理和全局过滤器实现
spring·spring cloud·gateway
matrixlzp8 天前
K8S Gateway AB测试、蓝绿发布、金丝雀(灰度)发布
kubernetes·gateway·ab测试
泽济天下9 天前
【工作记录】Kong Gateway 入门篇之部署及简单测试
gateway·kong
JAVA坚守者10 天前
API 网关核心功能解析:负载均衡、容灾、削峰降级原理与实战摘要
gateway·负载均衡·微服务架构·容灾备份·api 网关·削峰降级·云原生技术