首页 > 解决方案 > 对特定 URL 的 POST 请求需要 3 分钟

问题描述

我在服务器(生产)中对特定 URL 的所有 POST 类型请求都需要大约 3 分钟才能返回响应,也就是说,在我提交表单后几秒钟,我查看 API 站点并发布了我的数据,但在我的网站上,该请求处于待处理状态,恰好 3 分钟后,它完成了返回必要的数据。

我认为某些东西将响应保持了 3 分钟,因为我在本地环境中测试了相同的代码并且它运行得很快(大约需要 10 秒),是什么导致了这种“缓慢”?

在此处输入图像描述

看我的一小段代码,在本地环境下运行良好,但生产需要 3 分钟才能返回 API 结果。

public function __construct()
{

    $this->url = 'https://api.binance.com/api/';
    $this->curl = curl_init();
    $this->recvWindow = 60000;

    $curl_options = [
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_USERAGENT => 'Binance PHP API Agent',
        CURLOPT_RETURNTRANSFER => true,

    ];

    curl_setopt_array($this->curl, $curl_options);
}

private function privateRequest($url, $params = [], $method = 'GET')
{
    $params['timestamp'] = number_format((microtime(true) * 1000), 0, '.', '');
    $params['recvWindow'] = $this->recvWindow;

    $query = http_build_query($params, '', '&');

    $sign = hash_hmac('sha256', $query, $this->secret);

    $headers = array(
        'X-MBX-APIKEY: ' . $this->key,
    );

    curl_setopt($this->curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($this->curl, CURLOPT_URL, $this->url . $url . "?{$query}&signature={$sign}");

    curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($this->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($this->curl, CURLOPT_ENCODING, '');

    if ($method == "POST") {
        curl_setopt($this->curl, CURLOPT_POST, 1);
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, array());
    }

    if($method == 'GET'){
        curl_setopt($this->curl, CURLOPT_POST, false);
    }

    if ($method == 'DELETE') {
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, $method);
    }


    //Get result
    $result = curl_exec($this->curl);

    if ($result === false) {
        throw new \Exception('CURL error: ' . curl_error($this->curl));
    }

    // Decode results
    $result = json_decode($result, true);
    if (!is_array($result) || json_last_error()) {
        throw new \Exception('JSON decode Error');
    }

    return $result;
}

curl 不会产生任何错误,因为 API 返回状态 200 和所需数据,问题是返回响应需要 3 分钟。

注意:在其他 API 中,该帖子在生产环境中运行良好,最多在 5 秒内返回响应。

标签: phpcurl

解决方案


不确定参数中的时间戳和 recvWindow 的用途,但如果您使用它们来检查特定的时间窗口,那么我会确保服务器配置了正确的时区。


推荐阅读