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 Api Laravel Package

andrewmy/rabbitmq-management-api

PHP 7.1+/8 wrapper for the RabbitMQ Management HTTP API. Provides an object-oriented client for queues, exchanges, publish, and more, using PHP-HTTP/HTTPlug so you can plug in any compatible HTTP client (e.g., Guzzle adapter).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require andrewmy/rabbitmq-management-api php-http/guzzle7-adapter
    
    • Requires PHP 8.0+ and a PSR-18 HTTP client (Guzzle 7 recommended).
  2. First Use Case:

    • Initialize the client with RabbitMQ credentials:
      $client = new \RabbitMq\ManagementApi\Client(
          'http://guest:guest@localhost:15672/api',
          new \Http\Adapter\Guzzle\Guzzle17Adapter()
      );
      
    • Verify connection by listing vhosts:
      $vhosts = $client->vhosts()->get('/');
      
  3. Key Entry Points:

    • Queues: $client->queues()
    • Exchanges: $client->exchanges()
    • Bindings: $client->bindings()
    • Channels: $client->channels()

Implementation Patterns

Core Workflows

  1. Queue Management:

    • Declare a Queue:
      $client->queues()->declareQueue('/', 'my-queue', [
          'auto_delete' => false,
          'durable' => true,
      ]);
      
    • Publish a Message:
      $response = $client->exchanges()->publish('/', 'my-exchange', [
          'routing_key' => 'my-routing-key',
          'payload' => json_encode(['data' => 'test']),
          'payload_encoding' => 'application/json',
      ]);
      
  2. Exchange Operations:

    • List Exchanges:
      $exchanges = $client->exchanges()->get('/');
      
    • Delete an Exchange:
      $client->exchanges()->delete('/', 'unwanted-exchange');
      
  3. Consumer Monitoring:

    • List Consumers:
      $consumers = $client->consumers()->get('/', 'my-queue');
      
    • Cancel a Consumer:
      $client->consumers()->cancel('/', 'my-queue', $consumerTag);
      

Integration Tips

  • Error Handling: Use try/catch with \RabbitMq\ManagementApi\Exception\ApiException for HTTP errors.

    try {
        $client->queues()->purge('/', 'my-queue');
    } catch (\RabbitMq\ManagementApi\Exception\ApiException $e) {
        log::error('RabbitMQ API Error: ' . $e->getMessage());
    }
    
  • Bulk Operations: Leverage getAll() methods for large datasets (e.g., $client->queues()->getAll('/')).

  • Authentication: Use environment variables for credentials:

    $client = new \RabbitMq\ManagementApi\Client(
        sprintf('http://%s:%s@%s:%d/api',
            env('RABBITMQ_USER'),
            env('RABBITMQ_PASS'),
            env('RABBITMQ_HOST'),
            env('RABBITMQ_PORT')
        )
    );
    
  • Async Operations: Combine with Laravel Queues for delayed tasks:

    Queue::push(function () use ($client) {
        $client->queues()->purge('/', 'temp-queue');
    });
    

Gotchas and Tips

Pitfalls

  1. HTTP Client Compatibility:

    • Ensure your PSR-18 client (e.g., Guzzle 7) matches the package’s expectations.
    • Avoid mixing adapters (e.g., guzzle7-adapter vs. symfony-http-client).
  2. Rate Limiting:

    • RabbitMQ’s management API may throttle requests. Implement retries with exponential backoff:
      use Symfony\Component\HttpClient\RetryableHttpClient;
      $client = new RetryableHttpClient(
          new \Http\Adapter\Guzzle\Guzzle17Adapter(),
          [
              'max_retries' => 3,
              'delay' => 100,
              'multiplier' => 2,
          ]
      );
      
  3. Vhost Isolation:

    • Always specify the / (or correct vhost) in API paths. Omitting it defaults to /.
  4. Payload Encoding:

    • Default payload_encoding is 'string'. Use 'application/json' for structured data and handle serialization manually:
      $payload = json_encode(['key' => 'value'], JSON_THROW_ON_ERROR);
      

Debugging

  • Enable HTTP Logging: Configure Guzzle to log requests/responses:

    $client = new \Http\Adapter\Guzzle\Guzzle17Adapter(
        new \GuzzleHttp\Client([
            'handler' => \GuzzleHttp\HandlerStack::create(
                new \GuzzleHttp\Middleware::tap(function ($request, $options) {
                    \Log::debug('Request:', [
                        'url' => (string) $request->getUri(),
                        'method' => $request->getMethod(),
                    ]);
                })
            ),
        ])
    );
    
  • API Response Inspection: The package returns raw API responses. Use json_decode($response, true) to inspect structure:

    $response = $client->queues()->get('/', 'my-queue');
    \Log::debug('Queue Details:', $response);
    

Extension Points

  1. Custom HTTP Clients: Extend the Client class to add middleware or logging:

    class CustomClient extends \RabbitMq\ManagementApi\Client {
        public function __construct() {
            parent::__construct(
                'http://...',
                new \Http\Adapter\Guzzle\Guzzle17Adapter(),
                new \Http\Message\Formatter\SocketFactory()
            );
            $this->getHttpClient()->addMiddleware(...);
        }
    }
    
  2. Model Layer: Create domain-specific models to wrap API responses:

    class QueueModel {
        public function __construct(private array $data) {}
    
        public function getMessageCount(): int {
            return $this->data['messages'] ?? 0;
        }
    }
    
  3. Event Listeners: Use Laravel’s event system to react to queue/exchange changes:

    $client->queues()->declareQueue('/', 'event-queue', [], function ($response) {
        event(new QueueDeclared($response['name']));
    });
    

Configuration Quirks

  • Default Vhost: The package defaults to / (root vhost). Explicitly pass the vhost in all methods to avoid ambiguity.

  • Type Safety: The package uses loose typing for payloads. Validate inputs before publishing:

    $payload = is_string($payload) ? $payload : json_encode($payload);
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport