Home > OS >  Asynchronous consumption of queue to respond to frontend Requests
Asynchronous consumption of queue to respond to frontend Requests

Time:02-11

In my first attemps to get my head around asynchronous messaging for microservices in php. I built a registration form, sent the data using Ajax to a php script that publishes a message to a save queue and after that starts the while loop to consume a front end queue that's supposed to send the response as an echo back to ajax.

The Problem: starting the consumer in the same script called by ajax seems to be blocking, meaning that if any thing happens on the save service side, my server is busy, and I cann't even ^C it, and I have to kill the terminal manually!

how can I go about this?

My Ajax call:

$(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();
    });
  });

My 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();
}

CodePudding user response:

It's a very bad Idea to have used the Php server to test this application, Using Nginx or apache solved the Issue

  • Related