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.
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.
First Use Case:
use RabbitMQ\Management\APIClient;
$client = APIClient::factory(['url' => env('RABBITMQ_HOST', 'localhost')]);
$queue = $client->getQueue('/', 'my_queue');
return $queue->messages; // Returns pending messages count
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}"));
APIClient): Use in Laravel controllers/services for immediate feedback (e.g., dashboard metrics, CLI commands).AsyncAPIClient): Integrate with Laravel's queue workers or event listeners for background monitoring.RabbitMQ\Management\Entity\* classes (e.g., Queue, Exchange, Binding) for structured data.Queue Management
createQueue() or updateQueue() with entity flags (e.g., durable, autoDelete).
$queue = new Queue(['name' => 'orders', 'durable' => true]);
$client->createQueue($queue);
purgeQueue():
$client->purgeQueue('/', 'orders');
Monitoring
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();
}
public function handle(QueueMonitoringEvent $event) {
$client = AsyncAPIClient::factory($loop, ['url' => env('RABBITMQ_HOST')]);
$client->getQueue('/', 'critical_queue')
->then(fn($queue) => $this->alertIfOverThreshold($queue));
}
Bindings & Exchanges
$bindings = $client->listBindings('/', 'orders_exchange');
bindQueue():
$client->bindQueue('/', 'orders_exchange', 'orders_queue', ['routing_key' => 'order.created']);
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()}");
}
Async Limitations:
declareQueue with passive flag). Use synchronous client for these.$loop->run() in async scripts will block execution. For Laravel, offload async tasks to a separate process (e.g., using spatie/reactphp-laravel).Authentication:
$client = APIClient::factory([
'url' => env('RABBITMQ_HOST'),
'auth' => [env('RABBITMQ_USER'), env('RABBITMQ_PASS')],
]);
401 errors.Entity State:
name) are read-only. Attempting to set them will throw RuntimeException.durable, messages) when updating entities.Rate Limiting:
sleep(1); // Add delay between API calls
Deprecated Methods:
deleteQueu... (truncated in README) may not exist. Use deleteQueue() instead.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());
}
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);
}
}
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),
],
]);
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));
}
}
});
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,
],
],
]);
How can I help you explore Laravel packages today?