xlabs / rabbitmqbundle
RabbitMQ wrapper bundle
5.0.0
2024-03-18 16:59 UTC
Requires
- php: >=7.2
- php-amqplib/php-amqplib: 2.6.*
- symfony/framework-bundle: >=5.0
README
A Symfony2 RabbitMQ wrapper.
Installation
Install through composer:
php -d memory_limit=-1 composer.phar require xlabs/rabbitmqbundle
In your AppKernel
public function registerbundles()
{
return [
...
...
new XLabs\RabbitMQBundle\XLabsRabbitMQBundle(),
];
}
Configuration sample
Default values are shown below:
# app/config/config.yml
x_labs_rabbit_mq:
host: 192.168.5.26
port: 5672
vhost: '/'
user: admin
password: admin
exchange: gamification_exchange
api_port: 15672
queue_prefix: gamification_
Usage
First define your custom producer and its consumer:
# YourBundle/Resources/config/services.yml
...
my_custom_producer:
class: YourBundle\YourFolder\Producer
parent: xlabs_rmq_producer
shared: false
my_custom_consumer:
class: YourBundle\YourFolder\Consumer
tags:
- { name: console.command }
Your Producer class:
# YourBundle\YourFolder\Producer.php
namespace YourBundle\YourFolder;
use XLabs\RabbitMQBundle\RabbitMQ\Producer as Parent_Producer;
class Producer extends Parent_Producer
{
public static function getQueueName()
{
// set your custom queue name for this producer here
return 'my_custom_queue_name';
}
// if you need to modify the data sent in the message, create the following function
public function _process($data)
{
// here you can deal with the data in the message if needed before being consumed
}
}
Your Consumer class:
# YourBundle\YourFolder\Consumer.php
namespace YourBundle\YourFolder;
use XLabs\RabbitMQBundle\RabbitMQ\Consumer as Parent_Consumer;
class Consumer extends Parent_Consumer
{
// set your custom consumer command name
protected static $consumer = 'my_custom_name:bla_bla_bla';
// set a TTL > 0 to automatically close the consumer after period
// set TTL = 0 or dont set it to not close the consumer
protected $ttl = 0; // seconds
// following function is required as it is
protected function configure()
{
$this
->setName(self::$consumer)
;
}
// following function is required as it is
public function getQueueName()
{
return Producer::getQueueName();
}
public function callback($msg)
{
// this is all sample code to output something on screen
$container = $this->getApplication()->getKernel()->getContainer();
$msg = json_decode($msg->body);
echo "\n".$this->getQueueName()." - ".date('H:i:s d-m-Y')."\n";
echo "--------------------------------------------\n";
foreach($msg as $i => $tracker_item)
{
echo $i." : ".$tracker_item."\n";
}
}
}
At this point you can already call your producer:
$container->get('my_custom_producer')->process(array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
));
And running the consumer:
php app/console my_custom_name:bla_bla_bla
Requirements
Make sure to add "management" tag to the rabbitmq user in order to use the API.
sudo rabbitmqctl set_user_tags USERNAME management