WebFlux block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http

block()报错

WebFlux中,如果是Mono/Flux.map()或者其他方法体是属于NonBlocking线程,如果在NonBlocking线程中再调用阻塞方法(block()等)会报错

 final Optional<T> blockingGet() {
        if (Schedulers.isInNonBlockingThread()) {
            throw new IllegalStateException("blockOptional() is blocking, which is not supported in thread " + Thread.currentThread().getName());
        } else {
            RuntimeException re;
            if (this.getCount() != 0L) {
                try {
                    this.await();
                } catch (InterruptedException var3) {
                    this.dispose();
                    re = Exceptions.propagate(var3);
                    re.addSuppressed(new Exception("#blockOptional() has been interrupted"));
                    throw re;
                }
            }

            Throwable e = this.error;
            if (e != null) {
                re = Exceptions.propagate(e);
                re.addSuppressed(new Exception("#block terminated with an error"));
                throw re;
            } else {
                return Optional.ofNullable(this.value);
            }
        }
    }

其中Schedulers.isInNonBlockingThread()为

public static boolean isInNonBlockingThread() {
        return Thread.currentThread() instanceof NonBlocking;
    }

再此处会抛出错误。

解决方法

如果必须要获取java对象的话,通过新建线程操作,这样就不会触发isInNonBlockingThread(),可解决问题。

你可能感兴趣的:(webflux)