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 Management Client Laravel Package

alchemy/rabbitmq-management-client

PHP client for the RabbitMQ Management HTTP API. Query and manage queues, exchanges and more via synchronous Guzzle requests or asynchronous ReactPHP promises. Includes a Guarantee helper to ensure resources exist and match desired settings.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require alchemy/rabbitmq-management-client
    

    Add to composer.json if using Laravel's autoloader:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "RabbitMQ\\": "vendor/alchemy/rabbitmq-management-client/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case:

    • Synchronous Check: Verify a queue exists and its status:
      use RabbitMQ\Management\APIClient;
      
      $client = APIClient::factory(['url' => env('RABBITMQ_HOST', 'localhost')]);
      $queue = $client->getQueue('/', 'my_queue');
      return $queue->messages; // Returns pending messages count
      
    • Asynchronous Polling: Monitor queues in a Laravel job/queue worker:
      use RabbitMQ\Management\AsyncAPIClient;
      use React\EventLoop\LoopInterface;
      
      $loop = \React\EventLoop\Factory::create();
      $client = AsyncAPIClient::factory($loop, ['url' => env('RABBITMQ_HOST')]);
      
      $client->listQueues()
          ->then(fn($queues) => QueueMonitor::logQueues($queues))
          ->otherwise(fn($error) => Log::error("RabbitMQ error: {$error}"));
      

Key Entry Points

  • Synchronous (APIClient): Use in Laravel controllers/services for immediate feedback (e.g., dashboard metrics, CLI commands).
  • Asynchronous (AsyncAPIClient): Integrate with Laravel's queue workers or event listeners for background monitoring.
  • Entities: Explore RabbitMQ\Management\Entity\* classes (e.g., Queue, Exchange, Binding) for structured data.

Implementation Patterns

Common Workflows

  1. Queue Management

    • Create/Update: Use createQueue() or updateQueue() with entity flags (e.g., durable, autoDelete).
      $queue = new Queue(['name' => 'orders', 'durable' => true]);
      $client->createQueue($queue);
      
    • Purge: Clear messages with purgeQueue():
      $client->purgeQueue('/', 'orders');
      
  2. Monitoring

    • Periodic Checks: Combine with Laravel's task scheduling (app/Console/Kernel.php):
      protected function schedule(Schedule $schedule) {
          $schedule->call(function () {
              $client = APIClient::factory(['url' => env('RABBITMQ_HOST')]);
              $metrics = $client->listQueues();
              Metric::log(['queues' => $metrics]);
          })->everyMinute();
      }
      
    • Reactive Monitoring: Use async client in a Laravel event listener for real-time alerts:
      public function handle(QueueMonitoringEvent $event) {
          $client = AsyncAPIClient::factory($loop, ['url' => env('RABBITMQ_HOST')]);
          $client->getQueue('/', 'critical_queue')
              ->then(fn($queue) => $this->alertIfOverThreshold($queue));
      }
      
  3. Bindings & Exchanges

    • Inspect Bindings: List bindings for an exchange:
      $bindings = $client->listBindings('/', 'orders_exchange');
      
    • Create Bindings: Use bindQueue():
      $client->bindQueue('/', 'orders_exchange', 'orders_queue', ['routing_key' => 'order.created']);
      

Integration Tips

  • Laravel Service Provider: Bind the client to the container for dependency injection:

    public function register() {
        $this->app->singleton('rabbitmq', function () {
            return APIClient::factory(['url' => env('RABBITMQ_HOST')]);
        });
    }
    

    Usage in controllers:

    public function __construct(private APIClient $rabbitmq) {}
    
  • Async in Laravel: Use ReactPHP with Laravel's queue system (e.g., reactphp/queue package) for async operations:

    $loop = \React\EventLoop\Factory::create();
    $client = AsyncAPIClient::factory($loop, ['url' => env('RABBITMQ_HOST')]);
    
    $loop->addPeriodicTimer(60, function () use ($client) {
        $client->listQueues()->then(...);
    });
    
    // Run loop in a separate process or use `reactphp/queue` adapter.
    
  • Error Handling: Wrap calls in try-catch for EntityNotFoundException or HttpException:

    try {
        $client->getQueue('/', 'nonexistent');
    } catch (EntityNotFoundException $e) {
        Log::warning("Queue not found: {$e->getMessage()}");
    }
    

Gotchas and Tips

Pitfalls

  1. Async Limitations:

    • No Guaranteed API: Async client lacks support for operations requiring response guarantees (e.g., declareQueue with passive flag). Use synchronous client for these.
    • Loop Management: Forgetting to run $loop->run() in async scripts will block execution. For Laravel, offload async tasks to a separate process (e.g., using spatie/reactphp-laravel).
  2. Authentication:

    • Defaults to no auth. Configure credentials explicitly:
      $client = APIClient::factory([
          'url' => env('RABBITMQ_HOST'),
          'auth' => [env('RABBITMQ_USER'), env('RABBITMQ_PASS')],
      ]);
      
    • Missing auth may cause silent failures or 401 errors.
  3. Entity State:

    • Immutable Properties: Some entity properties (e.g., name) are read-only. Attempting to set them will throw RuntimeException.
    • Partial Updates: Only modify mutable fields (e.g., durable, messages) when updating entities.
  4. Rate Limiting:

    • RabbitMQ may throttle frequent requests. Add delays between calls in monitoring scripts:
      sleep(1); // Add delay between API calls
      
  5. Deprecated Methods:

    • Methods like deleteQueu... (truncated in README) may not exist. Use deleteQueue() instead.

Debugging

  • Enable Guzzle Debugging: Add to client config for HTTP traffic inspection:

    $client = APIClient::factory([
        'url' => env('RABBITMQ_HOST'),
        'debug' => true, // Enables Guzzle debug output
    ]);
    

    Logs will appear in Laravel's log channel.

  • Validate Entities: Use isValid() on entities to catch malformed data:

    $queue = new Queue(['name' => '', 'durable' => true]); // Invalid
    if (!$queue->isValid()) {
        throw new \InvalidArgumentException("Invalid queue: " . $queue->getErrors());
    }
    

Extension Points

  1. Custom Entities: Extend base entities (e.g., RabbitMQ\Management\Entity\Queue) to add application-specific fields:

    class AppQueue extends Queue {
        public $appMetadata;
    
        public function isValid() {
            $valid = parent::isValid();
            return $valid && isset($this->appMetadata);
        }
    }
    
  2. Middleware: Add HTTP middleware to the client for logging, retries, or auth:

    $client = APIClient::factory([
        'url' => env('RABBITMQ_HOST'),
        'middleware' => [
            new \RabbitMQ\Management\Middleware\LoggingMiddleware(),
            new \RabbitMQ\Management\Middleware\RetryMiddleware(3),
        ],
    ]);
    
  3. Event Dispatching: Trigger Laravel events on RabbitMQ state changes (e.g., queue depth thresholds):

    $client->listQueues()->then(function ($queues) {
        foreach ($queues as $queue) {
            if ($queue->messages > config('rabbitmq.alert_threshold')) {
                event(new QueueHighWaterEvent($queue));
            }
        }
    });
    

Configuration Quirks

  • URL Format: Ensure the URL includes the API path (http://localhost:15672/api/). The client appends /api/ if missing, but explicit URLs are safer:

    'url' => 'http://' . env('RABBITMQ_HOST') . ':15672/api/'
    
  • HTTPS: For HTTPS connections, provide the full URL and configure Guzzle options:

    $client = APIClient::factory([
        'url' => 'https://rabbitmq.example.com:15671/api/',
        'options' => [
            'curl' => [
                CURLOPT_SSL_VERIFYPEER => true,
                CURLOPT_SSL_VERIFYHOST => 2,
            ],
        ],
    ]);
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky