File not closed on Request “Complete” using guzzle 5.3

前提是你 提交于 2019-12-08 06:23:59

问题


We are uploading 1500+ files using a guzzle pool. Since we don't want to run into "too many open files" we figured we could use the event "before" to do the fopen and the "complete" to fclose the stream. PHP is not effectively closing the resource (and we hit the too many open files). Any idea what is happening / What we can do to fix this issue?

Here's the code:

    $client = new GuzzleHttp\Client();
    $requests = [];
    foreach($files as $fileName) {
        $options = [
            'debug' => false,
            'events' => [
                'before'=>
                    function (BeforeEvent $e) use ($fileName) {
                        echo 'Opening body|'.count(glob('/proc/'.posix_getpid().'/fd/*')).PHP_EOL;
                        $stream = \GuzzleHttp\Stream\Stream::factory(fopen($fileName,'r'));
                        $e->getRequest()->setBody($stream);
                    },
                'complete' =>
                    function (CompleteEvent $e){
                        echo 'Closing body|'.count(glob('/proc/'.posix_getpid().'/fd/*')).PHP_EOL;
                        $stream = $e->getResponse()->getBody();
                        $stream->close();
                    },
            ]
        ];

        $request = $client->createRequest('POST', $this->baseUri . $this->uploadPath, $options);
        $requests[] = $request;
    }
    Pool::batch($client, $requests, ['pool_size'=> $this->poolSize]);

Output : Opening body|31 Closing body|57 Opening body|57 Opening body|58 Closing body|59 Opening body|59 Closing body|61 Opening body|61 Closing body|62 Opening body|62 Closing body|63 ...

The number never goes down.


回答1:


You need to close the request's stream instead of the response one. The response stream seems to be closed automatically. So just replace

$stream = $e->getResponse()->getBody();

by

$stream = $e->getRequest()->getBody();

in your complete event



来源:https://stackoverflow.com/questions/32323140/file-not-closed-on-request-complete-using-guzzle-5-3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!