【问题标题】:PHP Curl Reuse In Thread线程中的 PHP Curl 重用
【发布时间】:2020-11-24 11:38:11
【问题描述】:

我想在线程中执行 curl 重用,如下所示:PHP Curl Reuse Optimization
但是当我执行这段代码时:

//main code
$n=0;
$app = [];

$app_default = new WebRequest();

for ($n = 0; $n < 50; $n++){

    $app[$n] = $app_default;
    $app[$n] -> start();

}
//
//base thread class
class WebRequest extends Thread {


    public function run() {
        $this->executeREUSEGET();
    }

        private $ch = null;

        function executeREUSEGET()
        {
            if ($this->ch == null) {
                $this->ch = curl_init();
                curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "GET");
                curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($this->ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
                curl_setopt($this->ch, CURLOPT_ENCODING, '');
            }
            curl_setopt($this->ch, CURLOPT_URL, 'https://www.google.com/');

            /* Result handling and processing */
            $result = curl_exec($this->ch);
            return $result;
        }
    
}

获取这些错误:

PHP Fatal error:  Uncaught RuntimeException: the creator of WebRequest already started it in D:\req.php:71

我该如何解决这个问题?

我不想在 loop.bcz 中的每个请求中执行 curl_unit() 和 curl_setopt() 它会变慢...
实际上我想在 pthread 的 while 循环中发送 curl 请求,bcz 速度对我来说非常重要,我不需要在每个请求中初始化 curl(url 和 curl_setopt 是静态的)。它会降低速度。

【问题讨论】:

    标签: php curl code-reuse php-pthread


    【解决方案1】:

    我找到了这段代码,但只能工作一次。这意味着只能获取一次网站内容:((

    $appa = new Atomic();
    $ok = $appa -> inc();
    //
    $n=0;
    $app = [];
    //
    for ($n = 0; $n < 50; $n++){
    
        $app[$n] = new WebRequest($ok);
        $app[$n] -> start();
    
    }
    ///
    class WebRequest extends Thread {
        
        public $ch;
    
        public function __construct($ch) {
            $this->ch = $ch;
        }
        
        public function run() {
                $result = curl_exec($this->ch);
                echo $result;
        }
    
    }
    ///
    class Atomic extends Threaded {
    
        public function inc() {
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
                curl_setopt($ch, CURLOPT_ENCODING, '');
                curl_setopt($ch, CURLOPT_URL, 'http://www.example.com');
                return $ch;
        }
    
        
    }
    

    【讨论】:

      猜你喜欢
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      • 2011-08-30
      • 1970-01-01
      • 1970-01-01
      • 2017-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多