什么是最佳实践,每秒通过 php 从队列中接收数据?我使用 ajax 查询来执行此操作,每秒调用一次 php 脚本。在那里,每次都会创建一个连接对象并声明一个队列。我第一次尝试将其保存在会话变量中,但是当我第二次调用 PHP 脚本时,我无法接收更多数据。当我调试通道对象时,我看到 is_open 是假的:
protected' is_open' => boolean false
这是我的基本 php 测试代码:
<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
session_start(); # start session handling.
$id = $_GET["uid"];
$connected = $_GET["connected"];
if (empty($id)) {
$id = 0;
}
$queue = 'CyOS EV Queue ' . $id;
$reset = $_GET["reset"];
if ($reset === "true") {
session_destroy();
$_SESSION = array();
echo "session destroyed";
var_dump($_SESSION);
exit;
}
$connection;
$channel;
if (!isset($_SESSION['coneccted'])) {
$_SESSION['coneccted'] = true;
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();
$channel->queue_declare($queue, false, false, false, false, false);
$channel->queue_bind($queue, 'CyOS-EX');
$_SESSION['connection'] = $connection;
$_SESSION['channel'] = $channel;
} else {
echo "already connected \n\r";
$connection = $_SESSION['connection'];
$channel = $_SESSION['channel'];
var_dump($_SESSION);
}
$test = new AMQPMessage();
while ($i < 10) {
echo "try to get data from " . $queue . "\n\r";
$test = $channel->basic_get($queue, true);
$i++;
if (isset($test)) {
echo "received data";
break;
}
}
echo $test->body;
当我每次调用脚本时初始化连接和通道时,它就会起作用。