Solon Cloud Gateway 开发:熟悉 Completable 响应式接口

Solon-Rx(约2Kb)是基于 reactive-streams 封装的 RxJava 极简版(约 2Mb 左右)。目前仅一个接口 Completable,意为:可完成的发布者。

使用场景及接口:

接口 说明
Completable 作为返回类型
Completable::complete() 构建完成发布者
Completable::error(cause) 构建异常发布者
Completable::create((emitter)->{...}) 构建发射器发布者

1、作为返回类型(主要用于过滤器)

java 复制代码
@FunctionalInterface
public interface ExFilter {
    /**
     * 过滤
     *
     * @param ctx   交换上下文
     * @param chain 过滤链
     */
    Completable doFilter(ExContext ctx, ExFilterChain chain);
}

2、构建返回对象(即,发布者)

java 复制代码
@Component
public class CloudGatewayFilterImpl implements CloudGatewayFilter {
    @Override
    public Completable doFilter(ExContext ctx, ExFilterChain chain) {
        String token = ctx.rawHeader("TOKEN");
        if (token == null) {
            ctx.newResponse().status(401);
            return Completable.complete();
        }
        
        return chain.doFilter(ctx);
    }
}

3、构建可发射控制的返回对象(比如做全局异常过滤)

java 复制代码
@Component(index = -99)
public class CloudGatewayFilterImpl implements CloudGatewayFilter {
    @Override
    public Completable doFilter(ExContext ctx, ExFilterChain chain) {
        return Completable.create(emitter -> {
            //订阅链路过滤的
            chain.doFilter(ctx).subscribe(new CompletableSubscriber() {
                @Override
                public void onError(Throwable e) {
                    ctx.newResponse().status(500);
                    emitter.onComplete();
                }

                @Override
                public void onComplete() {
                    emitter.onComplete();
                }
            });
        });
    }
}
相关推荐
小徐Chao努力13 小时前
【Langchain4j-Java AI开发】09-Agent智能体工作流
java·开发语言·人工智能
Coder_Boy_13 小时前
SpringAI与LangChain4j的智能应用-(理论篇3)
java·人工智能·spring boot·langchain
Coder_Boy_13 小时前
基于SpringAI的智能平台基座开发-(六)
java·数据库·人工智能·spring·langchain·langchain4j
伯明翰java14 小时前
Java数据类型与变量
java·开发语言
想用offer打牌14 小时前
如何开启第一次开源贡献之路?
java·后端·面试·开源·github
小许学java15 小时前
Spring原理
java·spring·生命周期·作用域·原理
教练、我想打篮球15 小时前
122 Hession,FastJson,ObjectInputStream的序列化反序列化相同引用的处理
java·config·utils
酷柚易汛15 小时前
酷柚易汛ERP 2025-12-26系统升级日志
java·前端·数据库·php
侠客行031716 小时前
Mybatis入门到精通 一
java·mybatis·源码阅读
消失的旧时光-194316 小时前
微服务的本质,其实是操作系统设计思想
java·大数据·微服务