Solon v3.2.1

熟悉 Completable 响应式接口

</> markdown

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

使用场景及接口:

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

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

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

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

@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、使用关注事件(比如做全局异常过滤)

@Component(index = -99)
public class CloudGatewayFilterImpl implements CloudGatewayFilter {
    @Override
    public Completable doFilter(ExContext ctx, ExFilterChain chain) {
        return chain.doFilter(ctx).doOnError(e -> {
            if (e instanceof StatusException) {
                StatusException se = (StatusException) e;

                ctx.newResponse().status(se.getCode());
            } else {
                ctx.newResponse().status(500);
            }
        });
    }
}