ahmedessam / lararabbit
A powerful and elegant RabbitMQ integration for Laravel microservices
Requires
- php: ^8.2
- illuminate/support: ^9.0|^10.0|^11.0|^12.0
- php-amqplib/php-amqplib: ^3.5
- rybakit/msgpack: ^0.9
Requires (Dev)
- orchestra/testbench: ^7.0|^8.0
- phpunit/phpunit: ^9.5
Suggests
- ext-msgpack: For faster MessagePack serialization/deserialization
- ext-pcntl: Required to use the parallel consumer functionality
- sentry/sentry-laravel: For detailed error tracking and monitoring
README
LaraRabbit is a powerful, feature-rich RabbitMQ integration package for Laravel designed specifically for microservices architecture. It provides an elegant abstraction over the PHP-AMQPLIB library with resilience patterns, performance optimizations, and developer-friendly features.
Features
- Simple, Expressive API: Intuitive interface for publishing and consuming messages
- Resilience Patterns: Circuit breaker and retry mechanisms to handle RabbitMQ outages gracefully
- Multiple Serialization Formats: Support for JSON and MessagePack serialization
- Message Validation: Schema validation for messages before publishing
- Dead Letter Queue Support: Built-in handling for failed messages
- Telemetry & Observability: Comprehensive logging and metrics
- Batch Processing Optimization: Efficient handling of large message batches
- CLI Commands: Artisan commands for common RabbitMQ management tasks
Installation
composer require ahmedessam/lararabbit
The package will automatically register its service provider if you're using Laravel's package auto-discovery.
Configuration
Publish the configuration file:
php artisan vendor:publish --tag=lararabbit-config
This will create a config/rabbitmq.php
file with all available configuration options.
Basic Usage
Publishing Messages
use AhmedEssam\LaraRabbit\Facades\RabbitMQ; // Simple publish RabbitMQ::publish('order.created', [ 'order_id' => 123, 'customer_id' => 456, 'amount' => 99.99 ]); // Publish with options RabbitMQ::publish('order.created', $data, [ 'message_id' => $uuid, 'priority' => 5, 'headers' => ['source' => 'api'] ]); // Publish event with automatic metadata RabbitMQ::publishEvent('OrderCreated', [ 'order_id' => 123, 'customer_id' => 456, 'amount' => 99.99 ]); // Batch publishing $messages = [ [ 'routingKey' => 'order.created', 'data' => ['order_id' => 123] ], [ 'routingKey' => 'order.created', 'data' => ['order_id' => 124] ] ]; RabbitMQ::publishBatch($messages);
Consuming Messages
use AhmedEssam\LaraRabbit\Facades\RabbitMQ; use PhpAmqpLib\Message\AMQPMessage; // Set up a queue and bind it to the exchange RabbitMQ::setupQueue('orders_service', ['order.created', 'order.updated']); // Consume messages from a queue RabbitMQ::consume('orders_service', function ($data, AMQPMessage $message) { // Process the message data echo "Received message: " . print_r($data, true); // If you return false, the message will not be acknowledged return true; });
Using Dead Letter Queues
use AhmedEssam\LaraRabbit\Facades\RabbitMQ; // Set up a queue with a dead letter queue for failed messages RabbitMQ::setupDeadLetterQueue( 'orders_service', 'orders_service_failed', ['order.failed'] ); // Consume messages from the dead letter queue RabbitMQ::consume('orders_service_failed', function ($data, $message) { // Process failed messages Log::error('Failed to process order', $data); });
CLI Commands
List all queues:
php artisan rabbitmq:list-queues
Purge a queue:
php artisan rabbitmq:purge-queue orders_service
Advanced Usage
Message Validation
// Register a schema app(MessageValidatorInterface::class)->registerSchema('order.created', [ 'order_id' => 'required|integer', 'customer_id' => 'required|integer', 'amount' => 'required|numeric' ]); // Publish with validation RabbitMQ::publish('order.created', $data, [ 'schema' => 'order.created' ]);
Serialization Formats
// Set serialization format globally RabbitMQ::setSerializationFormat('msgpack'); // Or use different formats for different messages RabbitMQ::setSerializationFormat('json')->publish('order.created', $data); RabbitMQ::setSerializationFormat('msgpack')->publish('inventory.updated', $data);
Connection Management
The package handles connections efficiently, but you can manually manage them:
// Get the connection manager $connectionManager = RabbitMQ::getConnectionManager(); // Close connection when done RabbitMQ::closeConnection();
Testing
The package includes a PHPUnit test suite. You can run the tests with:
composer test
You can also run individual test suites:
# Run only unit tests (no RabbitMQ connection required) composer test:unit # Run integration tests (requires RabbitMQ connection) composer test:integration
Integration tests require a running RabbitMQ server. They are skipped by default in the CI environment.
License
This package is open-sourced software licensed under the MIT license.
Security
Security Recommendations
When using LaraRabbit in production environments, consider these security recommendations:
-
Use SSL/TLS: Always enable the SSL connection to RabbitMQ in production environments by setting
RABBITMQ_SSL=true
and providing proper certificates. -
Custom Credentials: Never use the default guest/guest credentials in production. Create a dedicated user with appropriate permissions.
-
Message Validation: Always use schema validation for messages to prevent malformed data.
-
Secure Vhost: Use a dedicated virtual host for your application and limit access to it.
-
Network Segmentation: Place RabbitMQ behind a firewall and only allow connections from trusted sources.
Reporting Security Vulnerabilities
If you discover a security vulnerability within LaraRabbit, please send an email to aahmedessam30@gmail.com. All security vulnerabilities will be promptly addressed.
Contributing
Please see CONTRIBUTING for details on how to contribute to this package.