Skip to content

Instantly share code, notes, and snippets.

@heilgar
Last active Jun 4, 2019
Embed
What would you like to do?
PHP RabbitMQ Example for thewebland.net used docker-compose
{
"name": "thewebland/rabbitmq-php",
"description": "Usage example of RabbitMQ with php for thewebland.net",
"require": {
"php-amqplib/php-amqplib": "^2.9"
}
}
version: '3.0'
services:
rabbitmq:
image: rabbitmq:3.7.15-alpine
ports:
- "5672:5672"
environment:
RABBITMQ_DEFAULT_USER: "rabbitmq"
RABBITMQ_DEFAULT_PASS: "rabbitmq"
<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
$connection = new AMQPStreamConnection('localhost', 5672, 'rabbitmq', 'rabbitmq');
$channel = $connection->channel();
$channel->queue_declare('hello', false, false, false, false);
echo " [*] Waiting for messages. To exit press CTRL+C\n";
$callback = function ($msg) {
echo ' [x] Received ', $msg->body, "\n";
};
$channel->basic_consume('hello', '', false, true, false, false, $callback);
while (count($channel->callbacks)) {
$channel->wait();
}
<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
$connection = new AMQPStreamConnection('localhost', 5672, 'rabbitmq', 'rabbitmq');
$channel = $connection->channel();
$channel->queue_declare('hello', false, false, false, false);
$cliMessage = getopt(null, ["message:"]);
$msg = new AMQPMessage($cliMessage['message']);
$channel->basic_publish($msg, '', 'hello');
echo " [x] Sent '{$cliMessage["message"]}'\n";
$channel->close();
$connection->close();
0. docker-compose up -d
1. composer install
2. php receive.php
3. php send.php --message="Hello, World"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment