ahmedessam/lararabbit
Composer 安装命令:
composer require ahmedessam/lararabbit
包简介
A powerful and elegant RabbitMQ integration for Laravel applications, providing a simple and efficient way to manage message queues and event-driven architectures.
README 文档
README
LaraRabbit is a comprehensive, production-ready 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
- Automatic Reconnection: Smart reconnection with exponential backoff and configurable retry limits
- 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 with progress tracking
- Delivery Tag Caching: Improved reliability for message acknowledgement in complex scenarios
- Configurable Error Handling: Fine-grained control over error behavior
- Predefined Queues: Configure queues centrally and reuse them across your application
- Event Publishing: Structured events with automatic metadata and correlation tracking
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 files:
# Publish the main configuration file php artisan vendor:publish --tag=lararabbit-config # Publish the predefined queues configuration php artisan vendor:publish --tag=lararabbit-queues-config
This will create:
config/rabbitmq.phpfile with all general configuration optionsconfig/rabbitmq-queues.phpfile for predefined queue configurations
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 Predefined Queues
// Set up a predefined queue from configuration RabbitMQ::setupPredefinedQueue('order_service'); // Consume from a predefined queue RabbitMQ::consumeFromPredefinedQueue('order_service', function ($data, $message) { // Process the message data Log::info("Processing order", $data); 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 lararabbit:list-queues
Purge a queue:
php artisan lararabbit: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();
Error Handling and Reconnection
LaraRabbit provides robust error handling and automatic reconnection capabilities:
// Configure error handling options in config/rabbitmq.php 'consumer' => [ 'throw_exceptions' => false, // Whether to throw exceptions during processing 'reconnect_delay' => 5, // Seconds to wait before reconnection 'reconnect_max_retries' => 3, // Maximum reconnection attempts 'stop_on_critical_error' => false,// Whether to stop consumption on critical errors 'requeue_on_error' => false, // Whether to requeue failed messages ], // Consumption will automatically handle reconnection RabbitMQ::consume('orders_service', function ($data, $message) { try { // Process message return true; // Acknowledge on success } catch (\Exception $e) { // Failed messages will be handled according to configuration return false; // Reject the message } });
For more details on error handling, see ERROR_HANDLING.md.
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
Note: Some tests may fail if a RabbitMQ server is not available. This is expected behavior as certain tests require an actual connection to RabbitMQ. These tests are skipped by default in CI environments.
Documentation
LaraRabbit includes comprehensive documentation to help you get the most out of the package:
- Getting Started Guide - Essential steps to begin using LaraRabbit
- Configuration Guide - Detailed configuration options
- Publishing Messages - Advanced publishing techniques
- Consuming Messages - Consuming messages efficiently
- Error Handling - Robust error handling strategies
- Advanced Usage - Advanced patterns and techniques
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=trueand 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.
Credits
ahmedessam/lararabbit 适用场景与选型建议
ahmedessam/lararabbit 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 10 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 05 月 10 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「queue」 「rabbitmq」 「messaging」 「laravel」 「event-driven」 「microservices」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 ahmedessam/lararabbit 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 ahmedessam/lararabbit 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 ahmedessam/lararabbit 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Work with RabbitMQ in Laravel.
Microservice RPC through message queues.
PHP AMQP Binding Library
A Laravel package to monitor queue jobs.
PHP SDK for Mobile Message SMS API
Azure service bus Transport
统计信息
- 总下载量: 10
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 22
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-05-10