在 Linux 上模拟 HTTP POST 调用中的延迟

Simulating latency in a HTTP POST call on Linux

用例

我正在开发企业级支付应用程序(用 JAVA 编写)。我正在寻找模拟对银行进行的 HTTP POST 调用的延迟。这将使我能够模拟可能发生的不同 latency/unavailability 场景。

代码

以下代码将请求发送到银行:

try {
    // Set the location of the Bank Of America payment gateway
    URL url = new URL(getParameterGatewayUrl());

    // Open the connection
    urlConnection = url.openConnection();

    // Set the connection timeout
    urlConnection.setConnectTimeout(getTimeoutSeconds() * 1000);

    // Set the DoOutput flag to true because we intend
    // to use the URL connection for output
    urlConnection.setDoOutput(true);

    // Send the transaction via HTTPS POST
    OutputStream outputStream = urlConnection.getOutputStream();
    outputStream.write(postVars.getBytes());
    outputStream.close();
} catch (TimeoutException exception){

}

try {
    //Set the read timeout
    urlConnection.setReadTimeout(getTimeoutSeconds() * 1000);

    // Get the response from Bank Of America
    InputStream inputStream = urlConnection.getInputStream();
    while ((inputStreamCharacter = inputStream.read()) != -1)
        responseText.append((char) inputStreamCharacter);

    inputStream.close();
    LOG.debug("Bank Of America responseText: " + responseText);
} catch (SocketTimeoutException exception){

}

这段代码运行在异步支付任务中。

场景

事情是这样的:

  1. 我们连接到银行的支付网关
  2. 我们向银行发送付款请求。
  3. 我们等待银行回复我们的请求。
  4. 我们收到响应并对其进行解析并检查是否成功。

现在,我们想模拟请求发送到银行后的延迟,即在我们收到银行的响应之前。因此在第二个 try/catch 块中引发 SocketTimeoutException 异常。

问题

我需要处理的应用程序实例托管在服务器 VM 运行 14.04.1-Ubuntu 上。我过去在 windows 托管的应用程序上使用过 Fiddler to introduce latency。但棘手的是 Fiddler 是一个基于 UI 的程序,我无法在 Linux shell 上使用 over。 此外,我们没有得到银行的太多帮助。否则,如果这一切都在服务器端而不是在客户端进行模拟,那就容易多了。

问题

我已经用谷歌搜索了,但没能找到解决方案。有没有人尝试过这些方面的东西?如果是这样,我们该怎么做?欢迎任何建议。

我已经找到了测试这个的解决方法。我从 this answer. While httpbin is an amazing project it was missing the ability to delay the response of a POST request. Thus I forked their repository, and added the required endpoint myself. The fork 获得帮助,任何需要的人都可以得到帮助。

现在,只需将网关 URL 更改为基于带有 /post/delay/ 和延迟 [=] 的 httpbin 的 URL 18=] 请求响应将作为结果生成。

Fiddler是一个代理服务器;您可以简单地 运行 它在一台机器上(任何地方)并将 Linux 客户端的代理设置指向它。

有关详细信息,请参阅 Monitor Remote requests