【问题标题】:Transforming a Spring Webflux Mono to an Either, preferably without blocking?将 Spring Webflux Mono 转换为 Either,最好不阻塞?
【发布时间】:2018-04-24 11:23:46
【问题描述】:

我正在使用 Kotlin 和 Arrow 以及来自 spring-webfluxWebClient。我想做的是将Mono 实例转换为Either

Either 实例是通过在WebClient 的响应成功时调用Either.right(..) 或在WebClient 返回错误时调用Either.left(..) 创建的。

我正在寻找的是Mono 中类似于Either.fold(..) 的方法,我可以在其中映射成功和错误的结果并返回与Mono 不同的类型。像这样的东西(伪代码不起作用):

val either : Either<Throwable, ClientResponse> = 
                   webClient().post().exchange()
                                .fold({ throwable -> Either.left(throwable) },
                                      { response -> Either.right(response)})

应该怎么做?

【问题讨论】:

    标签: kotlin spring-webflux project-reactor arrow-kt


    【解决方案1】:

    Mono 上没有 fold 方法,但您可以使用两种方法实现相同的目的:maponErrorResume。它会是这样的:

    val either : Either<Throwable, ClientResponse> = 
                   webClient().post()
                              .exchange()
                              .map { Either.right(it) }
                              .onErrorResume { Either.left(it).toMono() }
    

    【讨论】:

      【解决方案2】:

      我不太熟悉 Arrow 库,也不熟悉它的典型用例,所以我将在这里使用 Java sn-ps 来说明我的观点。

      首先我想首先指出这种类型似乎是阻塞的而不是懒惰的(不像Mono)。将Mono 转换为该类型意味着您将使代码阻塞,并且您不应该这样做,例如,在控制器处理程序的中间,否则您将阻塞整个服务器。

      这或多或少相当于这个:

      Mono<ClientResponse> response = webClient.get().uri("/").exchange();
      // blocking; return the response or throws an exception
      ClientResponse blockingResponse = response.block();
      

      话虽如此,我认为您应该能够将Mono 转换为该类型,方法是在其上调用block() 并在其周围添加try/catch 块,或者先将其转换为CompletableFuture,喜欢:

      Mono<ClientResponse> response = webClient.get().uri("/").exchange();
      Either<Throwable, ClientResponse> either = response
              .toFuture()
              .handle((resp, t) -> Either.fold(t, resp))
              .get();
      

      可能有更好的方法来做到这一点(尤其是内联函数),但它们都应该首先阻止Mono

      【讨论】:

        猜你喜欢
        • 2018-11-12
        • 2021-07-14
        • 1970-01-01
        • 1970-01-01
        • 2022-01-11
        • 2015-08-17
        • 2018-06-09
        • 1970-01-01
        • 2021-02-06
        相关资源
        最近更新 更多