PHP中SystemV 消息队列实现多个客户和单个服务器之间复用消息

上一篇blog,简单记录了一下php中System V消息队列的相关知识。
这篇记录一下如何用php实现在多个客户和单个服务器之间复用消息。
如下图:
《PHP中SystemV 消息队列实现多个客户和单个服务器之间复用消息》
上图是一个很简单的模型。
下面是代码
server端代码:

<?php
$type = 1; // 服务器端从消息队列中获取的消息类型
$defaultPath = './index'; // 默认的请求文件路径
$queueKey = ftok(__FILE__,'a');
file_put_contents('./msg_queue.key',$queueKey);
$msgQueue = msg_get_queue($queueKey);
echo 'listening ....'."\n";
while (true) {
    msg_receive($msgQueue,$type,$msg_type,1024,$message);
    if ($message) {
        response($message, $msgQueue);
    }
    sleep(1);
}
function response($message, $msgQueue)
{
    if (empty($message) || empty($message['pid'])) {
        return false;
    }
    $pid = $message['pid'];
    $path = empty($message['path']) ? $defaultPath : $message['path'];
    $content = '';
    if ( file_exists($path) ) {
        $content = file_get_contents($path);
    }
    msg_send($msgQueue,$pid,$content);
}

客户端代码

<?php
$path = empty($argv[1]) ? './index' : $argv[1];
$keyFile= './msg_queue.key';
$queueKey = file_get_contents($keyFile);
if (empty($queueKey)) {
    die('no key in  file');
}
$msgQueue = msg_get_queue($queueKey);// 获取或创建一个消息队列,当这个队列不存在时,创建之,存在就返回。
$pid = getmypid();
// send request data to the server
$request = [
    'pid' => $pid,
    'path' => $path,
];
msg_send($msgQueue,1,$request);
// receive data from the server
while (1) {
    //msg_receive($msgQueue,$pid,$msgType,1024,$response,true,MSG_NOERROR);
    msg_receive($msgQueue,$pid,$msgType,1024,$response);
    if($response) {
        print_r($response);
        break;
    }
}

有个问题,当客户端请求的问题内容很多时,就出现阻塞了。。。。不过这个简单的模型算是练一下手吧。

    原文作者:helloworldcoding
    原文地址: https://segmentfault.com/a/1190000009159503
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞