通过RabbitMQ提供的API管理交换机

  列出所有交换机

<?php
declare(strict_types=1);
ini_set('display_errors', 'On');
error_reporting(-1);

// RabbitMQ接口服务器连接参数
$host = 'localhost';
$port = 15672;
$username = 'manong';
$password = '******';
$vhost = urlencode('/');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://$host:$port/api/exchanges/$vhost");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$response = curl_exec($ch);
curl_close($ch);

try {
    $exchanges = json_decode($response, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    exit('JsonException: ' . $e->getMessage());
}

foreach ($exchanges as $index => $exchange) {
    echo "---------- 交换机$index ----------" . PHP_EOL;
    echo "名称:{$exchange['name']}" . PHP_EOL;
    echo "类型:{$exchange['type']}" . PHP_EOL;
    echo "主机:{$exchange['vhost']}" . PHP_EOL;

    // 列出参数
    echo '参数:';
    if ($exchange['arguments']) {
        foreach ($exchange['arguments'] as $name => $argument) {
            echo "$name => $argument" . PHP_EOL;
        }
    } else {
        echo '无' . PHP_EOL;
    }

    echo PHP_EOL;
}



  删除指定交换机

<?php
declare(strict_types=1);
ini_set('display_errors', 'On');
error_reporting(-1);

// RabbitMQ接口服务器连接参数
$host = 'localhost';
$port = 15672; // 注意:端口是15672,而不是5672
$username = 'manong';
$password = '******';

$vhost = urlencode('/'); // 要删除的交换机的vhost
$exchange = 'test.exchange'; // 要删除的交换机名称

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://$host:$port/api/exchanges/$vhost/$exchange");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
$response = curl_exec($ch);
curl_close($ch);

// 删除失败时$response值示例:{"error":"Object Not Found","reason":"Not Found"}
if ($response === '') {
    echo "删除交换机[$exchange]成功"; // 删除交换机[test.exchange]成功
} else {
    echo "删除交换机[$exchange]失败:$response";
}


//========== 总结 ==========//
// 1、无法通过API删除x-delayed-message类型的交换机,虽然API响应结果是空字符串,但实际上并没有删除。

Copyright © 2024 码农人生. All Rights Reserved