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

发布时间:2019-08-08 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了PHP中SystemV 消息队列实现多个客户和单个服务器之间复用消息脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

上一篇blog简单记录了一下phpSystem V消息队列的相关知识。
这篇记录一下如何用php实现在多个客户和单个服务器之间复用消息。
如下图:
图片描述
上图是一个很简单的模型。
下面是代码
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;
    }
}

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

脚本宝典总结

以上是脚本宝典为你收集整理的PHP中SystemV 消息队列实现多个客户和单个服务器之间复用消息全部内容,希望文章能够帮你解决PHP中SystemV 消息队列实现多个客户和单个服务器之间复用消息所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。