PHP多进程异步执行处理的一种解决方案

233次阅读
没有评论

PHP 多进程异步执行处理的一种解决方案

核心思想上通过非阻塞模式的 http 请求去触发耗时任务,从而实现异步处理逻辑。

核心函数

// 异步请求 url

function _sock($url) {$host = parse_url($url,PHP_URL_HOST);
    $port = parse_url($url,PHP_URL_PORT);
    $port = $port ? $port : 80;
    $scheme = parse_url($url,PHP_URL_SCHEME);
    $path = parse_url($url,PHP_URL_PATH);
    $query = parse_url($url,PHP_URL_QUERY);
    if($query) $path .= '?'.$query;
    if($scheme == 'https') {$host = 'ssl://'.$host;}

    $fp = fsockopen($host,$port,$error_code,$error_msg,1);
    if(!$fp) {return array('error_code' => $error_code,'error_msg' => $error_msg);
    }
    else {stream_set_blocking($fp,true);// 开启了手册上说的非阻塞模式
        stream_set_timeout($fp,1);// 设置超时
        $header = "GET $path HTTP/1.1\r\n";
        $header.="Host: $host\r\n";
        $header.="Connection: close\r\n\r\n";// 长连接关闭
        fwrite($fp, $header);
        usleep(1000); // 这一句也是关键,如果没有这延时,可能在 nginx 服务器上就无法执行成功
        fclose($fp);
        return array('error_code' => 0);
    }
}

示例,项目地址为 http://local.test.com
入口文件 index.php

<?php

$url = 'http://local.test.com/test.php';

_sock($url);

echo 'game over';

耗时任务 test.php

<?php

set_time_limit(0);

file_put_contents('log.txt',date('Y-m-d H:i:s')."\n",FILE_APPEND);

sleep(60);

file_put_contents('log.txt',date('Y-m-d H:i:s')."\n",FILE_APPEND);

log.txt 文件执行记录

2023-04-05 22:29:26
2023-04-05 22:30:26

当请求 http://local.test.com/index.php 的时候,php 非阻塞模式请求 test.php,这样从而实现了多进程异步处理的思路。

因为 curl 扩展也可以实现非阻塞模式的 http 请求且 curl 有并发请求模式,也可以使用 curl 去实现异步执行方案。

正文完
有偿技术支持加微信
post-qrcode
 
评论(没有评论)
验证码