让workerman支持FastCGI协议:面向FastCGI-Client

blogdaren

关于workerman支持的版本:

根据老大的Merge情况来看,最小的版本可能是 version >= 4.0.40,协议实现请参考:
https://github.com/walkor/workerman/pull/784

为什么新增FastCGI协议支持?

  1. 首先源于问答社区里一个久远的帖子: https://www.workerman.net/q/1806
  2. 贴近workerman的应用生态,因为原来很多人的项目使用了php-fpm,新增的项目迁移到 workerman或者webman之后,还要保留原来的php-fpm项目, 难免会牵扯到FastCGI协议,另外他们的考虑就是我不一定非用nginx;
  3. 协议只照顾了客户端部分的实现,个人认为在workerman的生态圈中面向FastCGI-Server的实现意义不大。
  4. 其他略.....

准备一个基于PHP-FPM环境的CGI测试脚本:cgi.php

<?php
var_dump($_POST, $_GET, date('Y-m-d H:i:s'));

重点分享下应用层的基本用法:

<?php
use Workerman\Worker;
use Workerman\Protocols\FastCGI\Request;
use Workerman\Connection\AsyncTcpConnection;

require_once dirname(__FILE__, 1) . '/workerman/Autoloader.php';

$worker = new Worker();
$worker->name = "FastCGI-Client";

$worker->onWorkerStart = function($worker){
    //or use UNIX socket 
    $connection = new AsyncTcpConnection("unix:///tmp/fpm.sock");
    $connection->protocol = "\\Workerman\\Protocols\Fcgi";

    //or use TCP socket
    $connection = new AsyncTcpConnection("fcgi://127.0.0.1:9000");

    $connection->onConnect = function($connection){
        $total_request = 100;
        for($i = 0; $i < $total_request; $i++)
        {
            $request = new Request();
            $request->setScript("/path/to/script/cgi.php")
                ->setRequestMethod('post')
                ->setKeepAlive(true) //default is true
                ->setQueryString(['k1' => 'v1']) 
                ->setCustomParams(['k2' => 'v2'])
                ->appendCustomParams(['k3' => 'v3'])
                ->setContent(['number' => $i+1]);
            $connection->send($request);
        }
    };

    //这是暴露给开发者的一个回调,参数 $response 是响应对象
    $connection->onResponse = function($connection, $response){
        var_dump(
            $response->getHeader(), 
            $response->getBody(), 
            $response->getStdout(), 
            $response->getStderr(), 
            $response->formatOutput()
        );  
    };

    $connection->onMessage = function($connection, $data){
        var_dump($data)
        //打印接收到的响应数据 $data 如下所示
        /*Array
(
    [requestId] => 99
    [status] => 200
    [stderr] => 
    [header] => Array
        (
            [X-Powered-By] => PHP/7.4.16
            [Content-type] => text/html; charset=UTF-8
        )

    [body] => 2022-07-15 13:12:04
array(1) {
  ["number"]=>
  string(2) "99"
}
array(1) {
  ["k1"]=>
  string(2) "v1"
}
string(19) "2022-07-15 21:32:04"
)*/
    };

    $connection->onClose = function($connection){
    };

    $connection->connect();
};

Worker::runAll();
154 2 0
2个评论

liziyu

给你一个大大的赞👍

  • 暂无评论
luojianqun

  • 暂无评论

blogdaren

11886
积分
0
获赞数
0
粉丝数
2015-11-07 加入
🔝