SkillAgentSearch skills...

Bowler

RabbitMQ wrapper for Laravel

Install / Use

/learn @Vinelab/Bowler
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

Bowler

A Laravel package that implements the AMQP protocol using the Rabbitmq Server easily and efficiently. Built on top of the php-amqplib, with the aim of providing a simple abstraction layer to work with.

Build Status

Bowler allows you to:

  • Customize message publishing.
  • Customize message consumption.
  • Customize message dead lettering.
  • Handle application errors and deal with the corresponding messages accordingly.
  • Provide an expressive consumer queue setup.
  • Register a queue and generate it's message handler from the command line.
  • Make use of a default Pub/Sub messaging.

In addition to the above Bowler offers limited admin functionalities.

These features will facilitate drastically the way you use Rabbitmq and broaden its functionality. This package do not intend to take over the user's responsability of designing the messaging schema.

Tools like the Rabbitmq Management plugin, will certainly help you monitor the server's activity and visualize the setup.

Table of Contents

Setup<br> Development<br> Usage<br>    Producer<br>    Consumer<br>       Manual<br>       Console<br>    Publisher/Subscriber<br>    Dispatcher<br>    Dead Lettering<br>    Error Handling<br>    Error Reporting<br>    Health Checks<br>    Lifecycle Hooks<br>    Testing<br> Important Notes<br> Todo<br>

Supported Laravel versions

Starting version v0.4.2 this library requires Laravel 5.4 or later versions.

Starting version v0.5.0 this library requires Laravel 5.7 or later versions.

Starting version v0.9.0 this library requires Laravel 6.0 or later versions.

Setup

Install the package via Composer:

composer require vinelab/bowler

Laravel 5.4 users will also need to add the service provider to the providers array in config/app.php:

Vinelab\Bowler\BowlerServiceProvider::class,

After installation, you can publish the package configuration using the vendor:publish command. This command will publish the bowler.php configuration file to your config directory:

php artisan vendor:publish --provider="Vinelab\Bowler\BowlerServiceProvider"

You may configure RabbitMQ credentials in your .env file:

RABBITMQ_HOST=localhost
RABBITMQ_PORT=5672
RABBITMQ_USERNAME=guest
RABBITMQ_PASSWORD=guest

Development

Create the Docker container

docker-compose up -d

Bash into the container

docker-compose exec app bash

Install dependencies

composer install

Run tests

./vendor/bin/phpunit

Usage

Producer

In order to be able to send a message, a producer instance needs to be created and an exchange needs to be set up.

// Initialize a Bowler Connection
$connection = new Vinelab\Bowler\Connection();

// Initialize a Producer object with a connection
$bowlerProducer = new Vinelab\Bowler\Producer($connection);

// Setup the producer's exchange name and other optional parameters: exchange type, passive, durable, auto delete and delivery mode
$bowlerProducer->setup('reporting_exchange', 'direct', false, true, false, 2);

// Send a message with an optional routingKey
$bowlerProducer->send($data, 'warning');

or Inject the producer and let the IOC resolve the connection:

use Vinelab\Bowler\Producer;

class DoSomethingJob extends Job
{
    protected $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function handle(Producer $producer)
    {
        $producer->setup('reporting_exchange');

        $producer->send(json_encode($this->data));
    }
}

You need to make sure the exchange setup here matches the consumer's, otherwise a Vinelab\Bowler\Exceptions\DeclarationMismatchException is thrown.

If you mistakenly set an undefined value, setting up the exchange, e.g. $exchangeType='noneExistingType' a Vinelab\Bowler\Exceptions\InvalidSetupException is thrown.

Consumer

Add 'Registrator' => Vinelab\Bowler\Facades\Registrator::class, to the aliases array in config/app.

In order to consume a message an exchange and a queue needs to be set up and a message handler needs to be created.

Configuring the consumer can be done both manually or from the command line:

Manual

  1. Register your queues and handlers inside the queues.php file (think about the queues file as the routes file from Laravel), note that the queues.php file should be under App\Messaging directory:

    
    Registrator::queue('books', 'App\Messaging\Handlers\BookHandler', []);
    
    Registrator::queue('reporting', 'App\Messaging\Handlers\ErrorReportingHandler', [
                                                            'exchangeName' => 'main_exchange',
                                                            'exchangeType'=> 'direct',
                                                            'bindingKeys' => [
                                                                'warning',
                                                                'notification'
                                                            ],
                                                            'pasive' => false,
                                                            'durable' => true,
                                                            'autoDelete' => false,
                                                            'deadLetterQueueName' => 'dlx_queue',
                                                            'deadLetterExchangeName' => 'dlx',
                                                            'deadLetterExchangeType' => 'direct',
                                                            'deadLetterRoutingKey' => 'warning',
                                                            'messageTTL' => null
                                                        ]);
    
    

    Use the options array to setup your queues and exchanges. All of these are optional, defaults will apply to any parameters that are not specified here. The descriptions and defaults of these parameters are provided later in this document.

  2. Create your handlers classes to handle the received messages:

    // This is an example handler class
    
    namespace App\Messaging\Handlers;
    
    class AuthorHandler {
    
    	public function handle($msg)
    	{
    		echo "Author: ".$msg->body;
    	}
    
        public function handleError($e, $broker)
        {
            if($e instanceof InvalidInputException) {
                $broker->rejectMessage();
            } elseif($e instanceof WhatEverException) {
                $broker->ackMessage();
            } elseif($e instanceof WhatElseException) {
                $broker->nackMessage();
            } else {
                $msg = $broker->getMessage();
                if($msg->body) {
                    //
                }
            }
        }
    }
    

    Similarly to the above, additional functionality is also provided to the consumer's handler like deleteExchange, purgeQueue and deleteQueue. Use these wisely and take advantage of the unused and empty parameters. Keep in mind that it is not recommended that an application exception be handled by manipulating the server's setup.

Console

Register queues and handlers with php artisan bowler:make:queue {queue} {handler} e.g. php artisan bowler:make:queue analytics_queue AnalyticsData.

The previous command:

  1. Adds Registrator::queue('analytics_queue', 'App\Messaging\Handlers\AnalyticsDataHandler', []); to App\Messaging\queues.php.

    If no exchange name is provided the queue name will be used as default.

    The options array: if any option is specified it will override the parameter set in the command. This help to emphasize the queues.php file as a setup reference.

  2. Creates the App\Messaging\Handlers\AnalyticsDataHandler.php in App\Messaging\Handlers directory.

Now, in order to listen to any queue, run the following command from your console: php artisan bowler:consume {queue} e.g. php artisan bowler:consume analytics_queue. You need to specify the queue name and any other optional parameter, if applicable to your case.

bowler:consume complete arguments list description:

bowler:consume
queueName : The queue NAME
--N|exchangeName : The exchange NAME. Defaults to queueName.
--T|exchangeType : The exchange TYPE. Supported exchanges: fanout, direct, topic. Defaults to fanout.
--K|bindingKeys : The consumer\'s BINDING KEYS array.
--p|passive : If set, the server will reply with Declare-Ok if the exchange and queue already exists with the same name, and raise an error if not. Defaults to 0.
--d|durable : Mark exchange and queue as DURABLE. Defaults to 1.
--D|autoDelete : Set exchange and queue to AUTO DELETE when all queues and consumers, respectively have finished using it. Defaults to 0.
--deadLetterQueueName : The dead letter queue NAME. Defaults to deadLetterExchangeName.
--deadLetterExchangeName : The dead letter exchange NAME. Defaults to deadLetterQueueName.
--deadLetterExchangeType : The dead letter exchan

Related Skills

View on GitHub
GitHub Stars46
CategoryDevelopment
Updated1y ago
Forks7

Languages

PHP

Security Score

75/100

Audited on Mar 10, 2025

No findings