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();
                }
            });
        });
    }
}
相关推荐
全栈凯哥15 分钟前
Java详解LeetCode 热题 100(23):LeetCode 206. 反转链表(Reverse Linked List)详解
java·算法·leetcode·链表
小葡萄202515 分钟前
黑马程序员C++核心编程笔记--4 类和对象--多态
java·c++·笔记
Java之路行者25 分钟前
SpringBoot+XXL-JOB:高效定时任务管理
java·spring boot·后端·spring cloud
xrz27734 分钟前
JAVA获取ES连接并查询所有数据
java·elasticsearch
无妄-20241 小时前
“刹车思维”:慢,是为了更快
java·经验分享
玉~你还好吗1 小时前
【FreeRTOS#1】多任务处理&任务调度器&任务状态
java·开发语言
Yusei_05231 小时前
C++ 模版复习
android·java·c++
ytttr8731 小时前
k8s的出现解决了java并发编程胡问题了
java·容器·kubernetes
纪元A梦1 小时前
分布式拜占庭容错算法——权益证明(PoS)算法详解
java·分布式·算法
老友@1 小时前
Spring Boot 应用中实现配置文件敏感信息加密解密方案
java·spring boot·后端·数据安全·加密·配置文件