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();
                }
            });
        });
    }
}
相关推荐
布朗克1688 分钟前
Java 10 新特性及具体应用
java·开发语言·新特性·java10
ZZHow10243 小时前
JavaWeb开发_Day05
java·笔记·web
CHEN5_023 小时前
【Java虚拟机】垃圾回收机制
java·开发语言·jvm
Warren983 小时前
Lua 脚本在 Redis 中的应用
java·前端·网络·vue.js·redis·junit·lua
艾伦~耶格尔7 小时前
【数据结构进阶】
java·开发语言·数据结构·学习·面试
爪洼传承人7 小时前
18- 网络编程
java·网络编程
smileNicky8 小时前
SpringBoot系列之从繁琐配置到一键启动之旅
java·spring boot·后端
祈祷苍天赐我java之术8 小时前
Java 迭代器(Iterator)详解
java·开发语言
David爱编程8 小时前
为什么必须学并发编程?一文带你看懂从单线程到多线程的演进史
java·后端
我命由我123458 小时前
软件开发 - 避免过多的 if-else 语句(使用策略模式、使用映射表、使用枚举、使用函数式编程)
java·开发语言·javascript·设计模式·java-ee·策略模式·js