繁体   English   中英

使用php快速发送大量API请求?

[英]Sending a lot of API requests quickly with php?

我希望尽快做出一堆REST api调用。 我目前有大约1,000个请求。

任何处理或任何类似的事情都不需要这些调用的结果。 我只需要将它们全部发布到api url。

我当然在我的循环中尝试过很慢。 我也尝试过使用curl_multi_exec,但速度差不多。 这是代码。

foreach($users as $user){
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_USERAGENT, 'Mandrill-PHP/1.0.36');
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                curl_setopt($ch, CURLOPT_HEADER, false);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
                curl_setopt($ch, CURLOPT_TIMEOUT, 600);
                curl_setopt($ch, CURLOPT_URL, 'https://mandrillapp.com/api/1.0/messages/send.json');
                curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
                curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($mandril_message));

                curl_multi_add_handle($mh,$ch);
}
        $active = null;
        //execute the handles
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);

        while ($active && $mrc == CURLM_OK) {
            if (curl_multi_select($mh) != -1) {
            do {
                $mrc = curl_multi_exec($mh, $active);
            } while ($mrc == CURLM_CALL_MULTI_PERFORM);
            }
        }

关于如何快速做到这一点的任何想法。 我的其余代码只需要一秒钟左右即可完成,而不需要使用curl代码。

好的,所以我终于找到了一些时间来使用mandril api正常工作。 我从大约2000 api请求到1.处理时间从10分钟到6.8秒。

所以基本上你只需要确保你使用合并变量并为每组合并变量指定一个收件人。

以下是如何执行此操作的示例。

"to": [
        {
            "email": "recipient1.email@example.com"
        },
        {
            "email": "recipient2.email@example.com"
        }
    ],
"merge_vars": [
        {
            "rcpt": "recipient1.email@example.com",
            "vars": [
                {
                    "name": "FNAME",
                    "content": "John"
                },
                {
                    "name": "FEED",
                    "content": "Your personalized feed content here"
                }
            ],
            "rcpt": "recipient2.email@example.com",
            "vars": [
                {
                    "name": "FNAME",
                    "content": "Jane"
                },
                {
                    "name": "FEED",
                    "content": "Your personalized feed content here"
                }
            ]
        }
    ]

一千个REST请求将变得缓慢。 这里的技巧是异步运行作业,以便用户不受影响。 你可以向有问题的PHP脚本发送一个AJAX请求,并增强PHP脚本以在某处写入进度数据($ _SESSION,平面文件,数据库,等等。)然后你可以发送单独的AJAX调用来获取作业的进度并显示作业运行时对用户的更新。

这是假设这是我们在这里讨论的网页而不是shell脚本。

暂无
暂无

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

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