【问题标题】:How to use non-blocking HTTP requests in Mulesoft 4 Custom Connector如何在 Mulesoft 4 自定义连接器中使用非阻塞 HTTP 请求
【发布时间】:2020-12-02 10:03:27
【问题描述】:

我正在尝试构建一个 Mulesoft 自定义连接器,该连接器向第三方系统发出 HTTP 请求,我希望这些 HTTP 请求以非阻塞方式发出,以便执行可以继续而无需等待要返回的 HTTP 响应。

Mulesoft 文档here 中有一个示例,其中显示了此示例代码:

public void request(String url, @Connection HttpClient client, @Content String body, 
    CompletionCallback<InputStream, HttpAttributes> callback ) { 
 client.send(url, body, new HttpResponseCallback() {
   void onResponse(HttpResponse response) {
     callback.success(Result.<InputStream, HttpAttributes>builder() 
                          .output(response.getBody())
                          .attributes(toAttributes(response))
                          .build());
   }

   void onError(Exception e) {
     callback.error(e); 
   }
 });
}

它还声明可以提供非阻塞行为

通过支持异步响应的 HttpClient

Mulesoft's custom connector documentation 状态

HttpClient 能够使用非阻塞 I/O 来发出请求。

但我不明白怎么做!

上面的示例代码从HttpClient 接口调用了一个方法send(String, String, HttpResponseCallback)。但是,HttpClient 接口(如 Mulesoft's API javadoc 中所述)没有这样的方法。

我看到HttpClient 接口确实有sendAsync(HttpRequest request) 方法,但我无法理解如何将其与示例代码一起使用。

我了解 Mulesoft 的HttpClient 是使用 Project Grizzly 的 HTTP 客户端实现的,并且支持非阻塞请求,所以我觉得这是可以做到的,我只是不明白如何......

感谢任何提示!

【问题讨论】:

    标签: java http mule4 mule-sdk


    【解决方案1】:

    嗨,我试图用相同的 non-blocking-operations 文档实现同样的目标,但我做不到,所以我尝试基于 Slack connector,那里有很多例子,他们使用其他代码来实现异步调用ChannelOperations with CompletionCallback

    但是,这对我不起作用,我想也许我必须在服务器端进行另一种解决方法来实现异步调用。 无论如何,最后,我使用 CompletableFuture 在其他线程中运行请求, 请求是同步的,但是在 CompletableFuture.runAsync 中异步执行

    public void request(String url, @Connection HttpClient client, @Content String body) { 
    
    HttpResponse response = null;
    HttpEntity entity = new ByteArrayHttpEntity(body.toString().getBytes());
    HttpRequest httpRequest = HttpRequest.builder().uri(url).addHeader("Content-Type", "application/json")
                    .method("POST").entity(entity).build();
    CompletableFuture.runAsync(() -> {
     try {
                client.start();
                response = client.send(httpRequest, 30000, true, null);
            } catch (IOException | TimeoutException e) {
                    LOGGER.error(response.toString());
            }
        LOGGER.info(response.toString());
            client.stop();
        
        LOGGER.info("Finish");
    });
    }

    有一个类似于 DMI 的 Mule 连接器,其中调用是异步的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-29
      • 2016-07-05
      • 2013-11-12
      相关资源
      最近更新 更多