Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Rabbitmq Bundle Laravel Package

emag-tech-labs/rabbitmq-bundle

Abandoned RabbitMQ integration bundle for Symfony using php-amqplib. Provides producers, consumers, CLI commands, and common messaging patterns. Project is superseded by php-amqplib/rabbitmq-bundle (^2.6); migrate to that package.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require emag-tech-labs/rabbitmq-bundle
    

    (Note: Redirect to php-amqplib/RabbitMqBundle for active maintenance.)

  2. Configuration: Add to config/packages/rabbitmq.yaml:

    rabbit_mq:
        hosts:
            default:
                host:     'localhost'
                port:     5672
                user:     'guest'
                password: 'guest'
                vhost:    '/'
        connections:
            default:
                host: 'default'
        producers:
            default:
                connection: default
                exchange_options:
                    name: 'your_exchange'
                    type: direct
        consumers:
            default:
                connection: default
                queue: 'your_queue'
                callback: 'App\RabbitMQ\Consumer\YourConsumer'
                exchange_options:
                    name: 'your_exchange'
                    type: direct
    
  3. First Use Case: Publish a message from a controller:

    use RabbitMQ\Client;
    
    class MessageController extends AbstractController
    {
        public function send(Client $rabbitMQ)
        {
            $rabbitMQ->publish(
                'default',
                ['user_id' => 123, 'action' => 'login']
            );
        }
    }
    

Implementation Patterns

Core Workflows

  1. Producer Pattern:

    • Publish Messages:
      $rabbitMQ->publish('producer_name', $message, ['content_type' => 'application/json']);
      
    • Use Cases:
      • Async task dispatch (e.g., sending emails, processing orders).
      • Event-driven architectures (e.g., user actions triggering side effects).
  2. Consumer Pattern:

    • Define a Consumer Class:
      namespace App\RabbitMQ\Consumer;
      
      use RabbitMQ\Client;
      
      class OrderConsumer
      {
          public function execute($message, $messageInfo)
          {
              // Process $message (e.g., JSON decode, validate, handle)
              return true; // Acknowledge message
          }
      }
      
    • Register in config/packages/rabbitmq.yaml:
      consumers:
          order_consumer:
              callback: 'App\RabbitMQ\Consumer\OrderConsumer'
      
    • Start Consumers:
      php bin/console rabbitmq:consumer order_consumer
      
      (Use --auto-ack for auto-acknowledgment or --limit=10 for batch processing.)
  3. Message Serialization:

    • Default: Uses json_encode/json_decode. Override via serializer config:
      rabbit_mq:
          producers:
              default:
                  serializer: 'App\RabbitMQ\Serializer\CustomSerializer'
      
  4. Error Handling:

    • Retry Logic: Implement RabbitMQ\Client\ProducerInterface to customize retry behavior.
    • Dead Letter Exchanges: Configure in exchange_options:
      exchange_options:
          name: 'your_exchange'
          type: direct
          dead_letter_exchange: 'dlx_exchange'
      

Integration Tips

  1. Symfony Events: Bind RabbitMQ to Symfony events (e.g., kernel.request):

    use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
    use RabbitMQ\Client;
    
    class RabbitMQListener
    {
        public function onKernelResponse(FilterResponseEvent $event, Client $rabbitMQ)
        {
            $rabbitMQ->publish('events', ['event' => 'response', 'data' => $event->getResponse()->getContent()]);
        }
    }
    
  2. Dependency Injection:

    • Inject RabbitMQ\Client directly into services/controllers.
    • For consumers, use RabbitMQ\Client\ConsumerInterface for type-hinting.
  3. Testing:

    • Mock RabbitMQ\Client in PHPUnit:
      $this->createMock(RabbitMQ\Client::class);
      
    • Use RabbitMQ\Client\MockClient for integration tests (if available).
  4. Environment-Specific Configs: Override configs per environment (e.g., config/packages/rabbitmq/dev.yaml):

    rabbit_mq:
        hosts:
            default:
                host: 'rabbitmq-dev'
    

Gotchas and Tips

Pitfalls

  1. Abandoned Package:

  2. Connection Management:

    • Issue: Connections may hang if not closed properly.
    • Fix: Use try-catch blocks and ensure close() is called:
      try {
          $rabbitMQ->publish(...);
      } finally {
          $rabbitMQ->close();
      }
      
  3. Consumer Lifecycle:

    • Issue: Consumers may exit unexpectedly (e.g., unhandled exceptions).
    • Fix: Wrap consumer logic in try-catch and log errors:
      public function execute($message, $messageInfo)
      {
          try {
              // Process message
          } catch (\Exception $e) {
              \Log::error('Consumer error: ' . $e->getMessage());
              throw $e; // Reject message
          }
      }
      
  4. Message Ordering:

    • Issue: RabbitMQ does not guarantee message order by default.
    • Fix: Use priority in basic_publish or implement custom sequencing.
  5. Configuration Overrides:

    • Issue: Config changes may not reflect immediately.
    • Fix: Clear cache after config updates:
      php bin/console cache:clear
      

Debugging Tips

  1. Logs: Enable RabbitMQ logs in config/packages/rabbitmq.yaml:

    rabbit_mq:
        logging: true
    

    (Logs appear in Symfony’s monolog channel.)

  2. RabbitMQ Management UI:

    • Access http://localhost:15672 (default credentials: guest/guest).
    • Monitor queues, messages, and connections.
  3. Common Errors:

    • Connection refused: Verify host, port, and credentials.
    • No such exchange: Ensure exchange is declared before publishing.
    • Consumer timeout: Increase timeout in consumer config or optimize processing.

Extension Points

  1. Custom Serializers: Extend RabbitMQ\Client\Serializer\SerializerInterface:

    class CustomSerializer implements SerializerInterface
    {
        public function serialize($data) { /* ... */ }
        public function unserialize($data) { /* ... */ }
    }
    

    Register in config:

    rabbit_mq:
        producers:
            default:
                serializer: 'App\RabbitMQ\Serializer\CustomSerializer'
    
  2. Middleware: Add pre/post-processing to producers/consumers:

    $rabbitMQ->getProducer('default')->addMiddleware(new \App\RabbitMQ\Middleware\LoggingMiddleware());
    
  3. Dynamic Exchanges/Queues: Use RabbitMQ\Client\DynamicProducer for runtime declarations:

    $dynamicProducer = new DynamicProducer($connection, 'dynamic_exchange');
    $dynamicProducer->publish($message);
    
  4. Health Checks: Integrate with Symfony’s health system:

    use Symfony\Component\HealthCheck\RabbitMqConnectionCheck;
    
    services:
        Symfony\Component\HealthCheck\RabbitMqConnectionCheck:
            arguments:
                $rabbitMQ: '@rabbit_mq.client'
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime