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();
                }
            });
        });
    }
}
相关推荐
二两小咸鱼儿1 小时前
Java Demo - JUnit :Unit Test(Assert Methods)
java·后端·junit
字节源流1 小时前
【spring】配置类和整合Junit
java·后端·spring
跪在镜子前喊帅1 小时前
【面试】Java 多线程
java·面试
好看资源平台2 小时前
Java/Kotlin逆向基础与Smali语法精解
java·开发语言·kotlin
zimoyin2 小时前
解决 Java/Kotlin 资源加载问题
java·python·kotlin
阿木看源码3 小时前
bindingAdapter的异常错误
java·开发语言
跪在镜子前喊帅3 小时前
【面试】框架
java·面试
~Yogi4 小时前
每日学习Java之一万个为什么
java·开发语言·学习
Simon523144 小时前
数据结构---八大排序
java·数据结构·排序算法
WeiLai11124 小时前
面试基础--高并发高可用架构深度实践:降级熔断(Hystrix vs Sentinel)核心原理与源码解析
java·分布式·后端·hystrix·面试·架构·sentinel