简体   繁体   English

如何在 Mono/Flux 中调用 WebClient 方法?

[英]how to call WebClient methods inside Mono/Flux?

I'm new to reactive programming I call the "post" webclient method inside "mailTemplateMappinRepository.map()" in order not to interrupt the chain and pass the necessary parameters (data) to the "post" method我是反应式编程的新手,我在“mailTemplateMappinRepository.map()”中调用“post”webclient 方法,以免中断链并将必要的参数(数据)传递给“post”方法

I'm not sure if this is a good practice and if I need to call.subscribe() for the "post" method我不确定这是否是一个好习惯,我是否需要为“发布”方法调用.subscribe()


    return mailTemplateMappingRepository
        .findById(request.getTemplateKey())
        .switchIfEmpty(Mono.error(new MailTemplateNotSupportedException(
            "The template with key " + request.getTemplateKey() + " is not supported!!!")))
        .map(t -> {
          log.info("sendEmailWithRetry: request {}", request);
          log.info("sendEmailWithRetry: templateMappings {}", t);

          if (!businessUnitAuthTokens.containsKey(t.getExactTargetBusinessUnit())) {
            updateBusinessUnitToken(t);
          }

          String token = "Bearer " + businessUnitAuthTokens.get(t.getExactTargetBusinessUnit());
          String uri = exactTargetMessageDefinitionSendsUrl.replace("{key}", t.getExactTargetKey());
          Map<String, Object> mailTriggerPayload = generateMailTriggerPayload(request);

          RetryBackoffSpec is401RetrySpec = Retry.backoff(1, Duration.ofSeconds(2))
              .filter(throwable -> throwable instanceof Unauthorized)
              .doBeforeRetry(retrySignal -> {
                log.error("UNAUTHORIZED... WILL TRY AGAIN... Request: " + request);
                updateBusinessUnitToken(t);
              })
              .onRetryExhaustedThrow((retryBackoffSpec, retrySignal) ->
                  new ExactTargetException(HttpStatus.UNAUTHORIZED.value(), retrySignal.failure().getMessage(),
                      "There is something wrong with the authorization key for business unit: "
                          + request.getTemplateKey())
              );

          return restClientService.post(uri, mailTriggerPayload, token, String.class)
              .onErrorResume(error -> {
                if (error instanceof ExactTargetException) {
                  return Mono.error(new ExactTargetException(((ExactTargetException) error).getStatus(),
                      ((ExactTargetException) error).getBody(),
                      "Exact Target has errors... Status: " + ((ExactTargetException) error).getStatus()
                          + " Entity: "
                          + ((ExactTargetException) error).getBody()));
                }
                return Mono.error(error);
              }).retryWhen(is401RetrySpec).subscribe();
        });
  }

Are there any examples of applications or any other information on this topic?是否有关于此主题的任何应用示例或任何其他信息?

You're right about calling subscribe() in the middle of your chain.您在链的中间调用subscribe()是正确的。 Don't do that.不要那样做。

.map()  

semantically assumes that you want to map your object to another object or to change something within that object. This operation is synchronous.语义上假设你想要 map 你的 object 到另一个 object 或者改变那个 object 中的一些东西。这个操作是同步的。

However, WebClient calls return Publisher (some "promise") that can be either Mono or Flux但是, WebClient调用返回Publisher (一些“承诺”),它可以是MonoFlux

That means you should call it within .flatMap() that is asynchronous.这意味着您应该在异步的.flatMap()中调用它。

.flatMap()

Takes an object and returns some Publisher .采用 object 并返回一些Publisher So you should wrap your WebClient call to .flatMap() and you don't need to subscribe inside this operator.所以你应该将你的 WebClient 调用包装到.flatMap()并且你不需要在这个操作符中订阅。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM