在我第一次尝试了解 php 中微服务的异步消息传递时。我构建了一个注册表单,使用 Ajax 将数据发送到一个 php 脚本,该脚本将消息发布到一个保存队列,然后启动 while 循环以使用一个前端队列,该队列应该将响应作为echo
回传给 ajax。
问题:
在ajax调用的同一个脚本中启动消费者似乎是阻塞的,这意味着如果save
服务端发生任何事情,我的服务器很忙,我什至不能^C
,我必须手动杀死终端!
我该怎么办?
我的阿贾克斯电话:
$(document).ready(function () {
$("form").submit(function (event) {
var formData = {
name: $("#fullname").val(),
email: $("#email").val(),
password: $("#password").val()
};
$.ajax({
type: "POST",
url: "index.php",
data: { 'data' : JSON.stringify(formData) },
dataType: "json",
encode: true,
success : function(d){
console.log(d)
},
error : function(e){
console.log('error', typeof this.data)
}
})
event.preventDefault();
});
});
我的 index.php:
<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();
session_start();
$corr_id = uniqid();
$_SESSION['user'] = $corr_id;
error_log($_SESSION['user']);
error_log(session_id());
$channel->exchange_declare('Planning', 'topic', false, true, false, false, false);
$channel->queue_declare('front_queue', false, true, false, false);
$channel->queue_bind('front_queue', 'Planning', $corr_id);
$payload = json_decode($_POST['data'], true);
$payload += ["id" => $corr_id];
error_log(json_encode($payload));
$con = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$chan = $con->channel();
$chan->exchange_declare('Planning', 'topic', false, true, false);
$new_msg = new AMQPMessage(json_encode($payload), array('correlation_id' => $corr_id));
$chan->basic_publish($new_msg, 'Planning', 'save');
$chan->close();
$con->close();
$callback = function($msg)
{
$channel = $msg->getChannel();
$connection = $msg->getChannel()->getConnection();
echo json_encode($msg->body);
$msg->ack();
$channel->close();
$connection->close();
};
$channel->basic_consume('front_queue', '', false, false, false, false, $callback);
while($channel->is_open()){
$channel->wait();
}