Skip to content

RabbitMQ 虚拟主机管理

概述

虚拟主机(Virtual Host,简称 vhost)是 RabbitMQ 实现多租户隔离的核心机制。每个虚拟主机都是独立的消息队列环境,拥有自己的队列、交换器、绑定和权限。本文档详细介绍虚拟主机的概念、创建、管理和最佳实践。

核心知识点

虚拟主机概念

RabbitMQ 虚拟主机架构
┌─────────────────────────────────────────────────────────────┐
│                    RabbitMQ Server                          │
├─────────────────┬─────────────────┬─────────────────────────┤
│   vhost: /      │   vhost: /dev   │   vhost: /production    │
├─────────────────┼─────────────────┼─────────────────────────┤
│ ┌─────────────┐ │ ┌─────────────┐ │ ┌─────────────────────┐ │
│ │  Exchanges  │ │ │  Exchanges  │ │ │     Exchanges       │ │
│ └─────────────┘ │ └─────────────┘ │ └─────────────────────┘ │
│ ┌─────────────┐ │ ┌─────────────┐ │ ┌─────────────────────┐ │
│ │   Queues    │ │ │   Queues    │ │ │      Queues         │ │
│ └─────────────┘ │ └─────────────┘ │ └─────────────────────┘ │
│ ┌─────────────┐ │ ┌─────────────┐ │ ┌─────────────────────┐ │
│ │  Bindings   │ │ │  Bindings   │ │ │     Bindings        │ │
│ └─────────────┘ │ └─────────────┘ │ └─────────────────────┘ │
│ ┌─────────────┐ │ ┌─────────────┐ │ ┌─────────────────────┐ │
│ │ Permissions │ │ │ Permissions │ │ │    Permissions      │ │
│ └─────────────┘ │ └─────────────┘ │ └─────────────────────┘ │
└─────────────────┴─────────────────┴─────────────────────────┘

虚拟主机特性

特性说明
隔离性不同虚拟主机的资源完全隔离
独立性每个虚拟主机有独立的权限体系
命名空间队列和交换器名称在虚拟主机内唯一
资源限制可对每个虚拟主机设置资源限制
消息流消息不能跨虚拟主机传递

默认虚拟主机

RabbitMQ 安装后自动创建默认虚拟主机:

虚拟主机路径说明
默认 vhost/根虚拟主机,所有用户默认可访问

虚拟主机命名规范

推荐命名格式:

1. 环境隔离
   /dev          # 开发环境
   /test         # 测试环境
   /staging      # 预发布环境
   /production   # 生产环境

2. 服务隔离
   /order-service    # 订单服务
   /payment-service  # 支付服务
   /user-service     # 用户服务

3. 租户隔离
   /tenant-001   # 租户1
   /tenant-002   # 租户2

4. 混合模式
   /prod-order   # 生产-订单
   /prod-payment # 生产-支付

配置示例

rabbitmqctl 命令操作

bash
# ========================================
# 虚拟主机查询
# ========================================

# 列出所有虚拟主机
rabbitmqctl list_vhosts

# 列出虚拟主机详细信息
rabbitmqctl list_vhosts name tracing

# 查看虚拟主机中的队列
rabbitmqctl list_queues -p /vhost_name

# 查看虚拟主机中的交换器
rabbitmqctl list_exchanges -p /vhost_name

# 查看虚拟主机中的绑定
rabbitmqctl list_bindings -p /vhost_name

# ========================================
# 虚拟主机创建
# ========================================

# 创建虚拟主机
rabbitmqctl add_vhost /development
rabbitmqctl add_vhost /production
rabbitmqctl add_vhost /tenant_001

# ========================================
# 虚拟主机删除
# ========================================

# 删除虚拟主机(会删除其中所有资源)
rabbitmqctl delete_vhost /development

# ========================================
# 虚拟主机权限设置
# ========================================

# 为用户设置虚拟主机权限
rabbitmqctl set_permissions -p /development username ".*" ".*" ".*"
rabbitmqctl set_permissions -p /production username "^app-.*" "^app-.*" "^app-.*"

# 查看虚拟主机权限
rabbitmqctl list_permissions -p /development

# ========================================
# 虚拟主机追踪
# ========================================

# 启用追踪(用于调试)
rabbitmqctl trace_on -p /development

# 禁用追踪
rabbitmqctl trace_off -p /development

# ========================================
# 虚拟主机限制
# ========================================

# 设置队列数量限制
rabbitmqctl set_vhost_limits -p /development '{"max-queues": 100}'

# 设置连接数限制
rabbitmqctl set_vhost_limits -p /development '{"max-connections": 50}'

# 清除限制
rabbitmqctl clear_vhost_limits -p /development

# 查看限制
rabbitmqctl list_vhost_limits /development

HTTP API 操作

bash
# ========================================
# 虚拟主机查询
# ========================================

# 列出所有虚拟主机
curl -u admin:password http://localhost:15672/api/vhosts

# 获取特定虚拟主机
curl -u admin:password http://localhost:15672/api/vhosts/%2f

# 获取虚拟主机权限
curl -u admin:password http://localhost:15672/api/vhosts/%2f/permissions

# ========================================
# 虚拟主机创建
# ========================================

# 创建虚拟主机
curl -u admin:password -X PUT \
  http://localhost:15672/api/vhosts/development

# 创建带追踪的虚拟主机
curl -u admin:password -X PUT \
  -H "Content-Type: application/json" \
  -d '{"tracing":true}' \
  http://localhost:15672/api/vhosts/development

# ========================================
# 虚拟主机删除
# ========================================

curl -u admin:password -X DELETE \
  http://localhost:15672/api/vhosts/development

# ========================================
# 虚拟主机限制
# ========================================

# 设置限制
curl -u admin:password -X PUT \
  -H "Content-Type: application/json" \
  -d '{"max-queues":100,"max-connections":50}' \
  http://localhost:15672/api/vhost-limits/development

# 获取限制
curl -u admin:password \
  http://localhost:15672/api/vhost-limits/development

rabbitmq.conf 配置

ini
# ========================================
# 默认虚拟主机配置
# ========================================

# 默认虚拟主机
default_vhost = /

# 默认用户
default_user = guest
default_pass = guest

# ========================================
# 虚拟主机相关配置
# ========================================

# 默认虚拟主机统计模式
# collect_statistics = coarse

# 虚拟主机消息存储
# default_vhost = /

PHP 代码示例

虚拟主机管理类

php
<?php

class RabbitMQVHostManager
{
    private string $host;
    private int $apiPort;
    private string $username;
    private string $password;

    public function __construct(
        string $host = 'localhost',
        int $apiPort = 15672,
        string $username = 'guest',
        string $password = 'guest'
    ) {
        $this->host = $host;
        $this->apiPort = $apiPort;
        $this->username = $username;
        $this->password = $password;
    }

    private function request(string $endpoint, string $method = 'GET', $data = null): array
    {
        $url = "http://{$this->host}:{$this->apiPort}/api/{$endpoint}";
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_USERPWD => "{$this->username}:{$this->password}",
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_CUSTOMREQUEST => $method,
        ]);
        
        if ($data !== null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        return [
            'status' => $httpCode,
            'data' => json_decode($response, true),
        ];
    }

    private function encodeVhostName(string $name): string
    {
        return urlencode($name);
    }

    public function listVHosts(): array
    {
        $response = $this->request('vhosts');
        return $response['data'] ?? [];
    }

    public function getVHost(string $name): ?array
    {
        $response = $this->request("vhosts/{$this->encodeVhostName($name)}");
        
        if ($response['status'] === 404) {
            return null;
        }
        
        return $response['data'];
    }

    public function createVHost(string $name, bool $tracing = false): bool
    {
        $data = $tracing ? ['tracing' => true] : null;
        $response = $this->request(
            "vhosts/{$this->encodeVhostName($name)}",
            'PUT',
            $data
        );
        
        return in_array($response['status'], [201, 204]);
    }

    public function deleteVHost(string $name): bool
    {
        $response = $this->request(
            "vhosts/{$this->encodeVhostName($name)}",
            'DELETE'
        );
        
        return $response['status'] === 204;
    }

    public function getVHostPermissions(string $name): array
    {
        $response = $this->request("vhosts/{$this->encodeVhostName($name)}/permissions");
        return $response['data'] ?? [];
    }

    public function getVHostLimits(string $name): array
    {
        $response = $this->request("vhost-limits/{$this->encodeVhostName($name)}");
        return $response['data'] ?? [];
    }

    public function setVHostLimits(string $name, int $maxQueues = null, int $maxConnections = null): bool
    {
        $limits = [];
        
        if ($maxQueues !== null) {
            $limits['max-queues'] = $maxQueues;
        }
        
        if ($maxConnections !== null) {
            $limits['max-connections'] = $maxConnections;
        }
        
        if (empty($limits)) {
            return false;
        }
        
        $response = $this->request(
            "vhost-limits/{$this->encodeVhostName($name)}",
            'PUT',
            $limits
        );
        
        return in_array($response['status'], [201, 204]);
    }

    public function clearVHostLimits(string $name): bool
    {
        $response = $this->request(
            "vhost-limits/{$this->encodeVhostName($name)}",
            'DELETE'
        );
        
        return $response['status'] === 204;
    }

    public function getVHostQueues(string $name): array
    {
        $response = $this->request("queues/{$this->encodeVhostName($name)}");
        return $response['data'] ?? [];
    }

    public function getVHostExchanges(string $name): array
    {
        $response = $this->request("exchanges/{$this->encodeVhostName($name)}");
        return $response['data'] ?? [];
    }

    public function getVHostStats(string $name): array
    {
        $vhost = $this->getVHost($name);
        
        if (!$vhost) {
            return [];
        }
        
        $queues = $this->getVHostQueues($name);
        $exchanges = $this->getVHostExchanges($name);
        
        $messageCount = 0;
        $consumerCount = 0;
        
        foreach ($queues as $queue) {
            $messageCount += $queue['messages'] ?? 0;
            $consumerCount += $queue['consumers'] ?? 0;
        }
        
        return [
            'name' => $name,
            'tracing' => $vhost['tracing'] ?? false,
            'queues' => count($queues),
            'exchanges' => count($exchanges),
            'messages' => $messageCount,
            'consumers' => $consumerCount,
        ];
    }

    public function printVHostList(): void
    {
        $vhosts = $this->listVHosts();
        
        echo "RabbitMQ 虚拟主机列表\n";
        echo str_repeat("=", 60) . "\n";
        echo sprintf("%-20s %-10s %-10s %-10s\n", '名称', '追踪', '队列数', '消息数');
        echo str_repeat("-", 60) . "\n";
        
        foreach ($vhosts as $vhost) {
            $name = $vhost['name'];
            $tracing = ($vhost['tracing'] ?? false) ? '是' : '否';
            $stats = $this->getVHostStats($name);
            
            echo sprintf("%-20s %-10s %-10d %-10d\n",
                $name,
                $tracing,
                $stats['queues'],
                $stats['messages']
            );
        }
    }
}

// 使用示例
$vhostManager = new RabbitMQVHostManager('localhost', 15672, 'admin', 'password');

// 创建虚拟主机
$vhostManager->createVHost('/development');
$vhostManager->createVHost('/production');

// 设置限制
$vhostManager->setVHostLimits('/development', 100, 50);

// 打印列表
$vhostManager->printVHostList();

环境隔离管理类

php
<?php

class EnvironmentVHostSetup
{
    private RabbitMQVHostManager $vhostManager;

    public function __construct(RabbitMQVHostManager $vhostManager)
    {
        $this->vhostManager = $vhostManager;
    }

    public function setupEnvironment(string $env, array $config = []): array
    {
        $vhostName = "/{$env}";
        
        $defaults = [
            'max_queues' => match ($env) {
                'development' => 50,
                'test' => 100,
                'staging' => 200,
                'production' => 500,
                default => 100,
            },
            'max_connections' => match ($env) {
                'development' => 20,
                'test' => 50,
                'staging' => 100,
                'production' => 200,
                default => 50,
            },
            'tracing' => $env !== 'production',
        ];
        
        $config = array_merge($defaults, $config);
        
        $this->vhostManager->createVHost($vhostName, $config['tracing']);
        $this->vhostManager->setVHostLimits(
            $vhostName,
            $config['max_queues'],
            $config['max_connections']
        );
        
        return [
            'vhost' => $vhostName,
            'config' => $config,
        ];
    }

    public function setupAllEnvironments(): array
    {
        $environments = ['development', 'test', 'staging', 'production'];
        $results = [];
        
        foreach ($environments as $env) {
            $results[$env] = $this->setupEnvironment($env);
        }
        
        return $results;
    }

    public function destroyEnvironment(string $env): bool
    {
        $vhostName = "/{$env}";
        return $this->vhostManager->deleteVHost($vhostName);
    }
}

// 使用示例
$setup = new EnvironmentVHostSetup($vhostManager);

// 设置所有环境
$results = $setup->setupAllEnvironments();
print_r($results);

// 设置单个环境
$setup->setupEnvironment('production', [
    'max_queues' => 1000,
    'max_connections' => 500,
    'tracing' => false,
]);

租户隔离管理类

php
<?php

class TenantVHostManager
{
    private RabbitMQVHostManager $vhostManager;
    private string $prefix;

    public function __construct(RabbitMQVHostManager $vhostManager, string $prefix = 'tenant')
    {
        $this->vhostManager = $vhostManager;
        $this->prefix = $prefix;
    }

    public function createTenant(string $tenantId, array $limits = []): array
    {
        $vhostName = "/{$this->prefix}_{$tenantId}";
        
        $defaultLimits = [
            'max_queues' => 50,
            'max_connections' => 20,
        ];
        
        $limits = array_merge($defaultLimits, $limits);
        
        $this->vhostManager->createVHost($vhostName);
        $this->vhostManager->setVHostLimits(
            $vhostName,
            $limits['max_queues'],
            $limits['max_connections']
        );
        
        return [
            'tenant_id' => $tenantId,
            'vhost' => $vhostName,
            'limits' => $limits,
        ];
    }

    public function deleteTenant(string $tenantId): bool
    {
        $vhostName = "/{$this->prefix}_{$tenantId}";
        return $this->vhostManager->deleteVHost($vhostName);
    }

    public function getTenantStats(string $tenantId): array
    {
        $vhostName = "/{$this->prefix}_{$tenantId}";
        return $this->vhostManager->getVHostStats($vhostName);
    }

    public function listTenants(): array
    {
        $vhosts = $this->vhostManager->listVHosts();
        $tenants = [];
        
        foreach ($vhosts as $vhost) {
            $name = $vhost['name'];
            if (str_starts_with($name, "/{$this->prefix}_")) {
                $tenantId = substr($name, strlen("/{$this->prefix}_"));
                $tenants[$tenantId] = [
                    'tenant_id' => $tenantId,
                    'vhost' => $name,
                    'stats' => $this->vhostManager->getVHostStats($name),
                ];
            }
        }
        
        return $tenants;
    }

    public function updateTenantLimits(string $tenantId, array $limits): bool
    {
        $vhostName = "/{$this->prefix}_{$tenantId}";
        
        return $this->vhostManager->setVHostLimits(
            $vhostName,
            $limits['max_queues'] ?? null,
            $limits['max_connections'] ?? null
        );
    }
}

// 使用示例
$tenantManager = new TenantVHostManager($vhostManager, 'tenant');

// 创建租户
$tenantManager->createTenant('001', ['max_queues' => 100, 'max_connections' => 30]);
$tenantManager->createTenant('002', ['max_queues' => 50, 'max_connections' => 20]);

// 列出所有租户
$tenants = $tenantManager->listTenants();
print_r($tenants);

虚拟主机监控类

php
<?php

class VHostMonitor
{
    private RabbitMQVHostManager $vhostManager;

    public function __construct(RabbitMQVHostManager $vhostManager)
    {
        $this->vhostManager = $vhostManager;
    }

    public function getHealthStatus(string $vhostName): array
    {
        $stats = $this->vhostManager->getVHostStats($vhostName);
        $limits = $this->vhostManager->getVHostLimits($vhostName);
        
        $issues = [];
        $warnings = [];
        
        if (!empty($limits)) {
            $maxQueues = $limits['max-queues'] ?? PHP_INT_MAX;
            $maxConnections = $limits['max-connections'] ?? PHP_INT_MAX;
            
            $queueUsage = $stats['queues'] / $maxQueues;
            $connectionUsage = $stats['consumers'] / $maxConnections;
            
            if ($queueUsage > 0.9) {
                $issues[] = "队列数量接近上限: {$stats['queues']}/{$maxQueues}";
            } elseif ($queueUsage > 0.7) {
                $warnings[] = "队列数量使用率较高: " . round($queueUsage * 100, 1) . "%";
            }
            
            if ($connectionUsage > 0.9) {
                $issues[] = "连接数接近上限: {$stats['consumers']}/{$maxConnections}";
            } elseif ($connectionUsage > 0.7) {
                $warnings[] = "连接数使用率较高: " . round($connectionUsage * 100, 1) . "%";
            }
        }
        
        if ($stats['messages'] > 100000) {
            $warnings[] = "消息堆积严重: {$stats['messages']} 条";
        }
        
        return [
            'vhost' => $vhostName,
            'stats' => $stats,
            'limits' => $limits,
            'issues' => $issues,
            'warnings' => $warnings,
            'healthy' => empty($issues),
        ];
    }

    public function monitorAll(): array
    {
        $vhosts = $this->vhostManager->listVHosts();
        $results = [];
        
        foreach ($vhosts as $vhost) {
            $results[$vhost['name']] = $this->getHealthStatus($vhost['name']);
        }
        
        return $results;
    }

    public function printHealthReport(): void
    {
        $results = $this->monitorAll();
        
        echo "RabbitMQ 虚拟主机健康报告\n";
        echo "生成时间: " . date('Y-m-d H:i:s') . "\n";
        echo str_repeat("=", 70) . "\n\n";
        
        foreach ($results as $vhost => $health) {
            $status = $health['healthy'] ? '✅ 健康' : '❌ 异常';
            echo "虚拟主机: {$vhost}\n";
            echo "状态: {$status}\n";
            echo "队列: {$health['stats']['queues']}\n";
            echo "消息: {$health['stats']['messages']}\n";
            echo "消费者: {$health['stats']['consumers']}\n";
            
            if (!empty($health['issues'])) {
                echo "问题:\n";
                foreach ($health['issues'] as $issue) {
                    echo "  ❌ {$issue}\n";
                }
            }
            
            if (!empty($health['warnings'])) {
                echo "警告:\n";
                foreach ($health['warnings'] as $warning) {
                    echo "  ⚠️  {$warning}\n";
                }
            }
            
            echo str_repeat("-", 70) . "\n";
        }
    }
}

// 使用示例
$monitor = new VHostMonitor($vhostManager);
$monitor->printHealthReport();

实际应用场景

场景一:开发测试生产环境隔离

php
<?php

class EnvironmentIsolationSetup
{
    private RabbitMQVHostManager $vhostManager;

    public function setup(): void
    {
        $environments = [
            'development' => [
                'max_queues' => 50,
                'max_connections' => 20,
                'tracing' => true,
            ],
            'testing' => [
                'max_queues' => 100,
                'max_connections' => 50,
                'tracing' => true,
            ],
            'staging' => [
                'max_queues' => 200,
                'max_connections' => 100,
                'tracing' => false,
            ],
            'production' => [
                'max_queues' => 500,
                'max_connections' => 200,
                'tracing' => false,
            ],
        ];

        foreach ($environments as $env => $config) {
            $this->vhostManager->createVHost("/{$env}", $config['tracing']);
            $this->vhostManager->setVHostLimits(
                "/{$env}",
                $config['max_queues'],
                $config['max_connections']
            );
        }
    }
}

场景二:SaaS 多租户架构

php
<?php

class SaaSMultiTenantSetup
{
    private TenantVHostManager $tenantManager;

    public function onboardTenant(string $tenantId, string $plan): array
    {
        $limits = match ($plan) {
            'free' => ['max_queues' => 10, 'max_connections' => 5],
            'basic' => ['max_queues' => 50, 'max_connections' => 20],
            'pro' => ['max_queues' => 200, 'max_connections' => 100],
            'enterprise' => ['max_queues' => 1000, 'max_connections' => 500],
            default => ['max_queues' => 10, 'max_connections' => 5],
        };

        return $this->tenantManager->createTenant($tenantId, $limits);
    }

    public function upgradeTenant(string $tenantId, string $newPlan): bool
    {
        $limits = match ($newPlan) {
            'basic' => ['max_queues' => 50, 'max_connections' => 20],
            'pro' => ['max_queues' => 200, 'max_connections' => 100],
            'enterprise' => ['max_queues' => 1000, 'max_connections' => 500],
            default => ['max_queues' => 10, 'max_connections' => 5],
        };

        return $this->tenantManager->updateTenantLimits($tenantId, $limits);
    }
}

场景三:微服务隔离

php
<?php

class MicroserviceVHostSetup
{
    private RabbitMQVHostManager $vhostManager;

    public function setupService(string $serviceName, array $config = []): array
    {
        $vhostName = "/svc_{$serviceName}";
        
        $defaults = [
            'max_queues' => 50,
            'max_connections' => 30,
            'tracing' => false,
        ];
        
        $config = array_merge($defaults, $config);
        
        $this->vhostManager->createVHost($vhostName, $config['tracing']);
        $this->vhostManager->setVHostLimits(
            $vhostName,
            $config['max_queues'],
            $config['max_connections']
        );
        
        return [
            'service' => $serviceName,
            'vhost' => $vhostName,
            'config' => $config,
        ];
    }

    public function setupAllServices(): array
    {
        $services = [
            'order' => ['max_queues' => 100, 'max_connections' => 50],
            'payment' => ['max_queues' => 50, 'max_connections' => 30],
            'inventory' => ['max_queues' => 30, 'max_connections' => 20],
            'notification' => ['max_queues' => 20, 'max_connections' => 10],
        ];
        
        $results = [];
        foreach ($services as $service => $config) {
            $results[$service] = $this->setupService($service, $config);
        }
        
        return $results;
    }
}

常见问题与解决方案

问题一:无法创建虚拟主机

原因分析

  • 用户权限不足
  • 虚拟主机名称格式错误
  • 已存在同名虚拟主机

解决方案

bash
# 检查用户权限(需要管理员标签)
rabbitmqctl list_users | grep admin

# 检查现有虚拟主机
rabbitmqctl list_vhosts

# 正确创建虚拟主机
rabbitmqctl add_vhost /my_vhost

# 注意:虚拟主机名称建议以 / 开头

问题二:删除虚拟主机后资源丢失

原因分析

  • 删除虚拟主机会删除其中所有资源
  • 没有备份

解决方案

bash
# 删除前备份
# 导出定义
curl -u admin:password http://localhost:15672/api/definitions -o backup.json

# 查看虚拟主机资源
rabbitmqctl list_queues -p /vhost_name
rabbitmqctl list_exchanges -p /vhost_name

# 确认后再删除
rabbitmqctl delete_vhost /vhost_name

问题三:虚拟主机限制不生效

原因分析

  • 限制格式错误
  • RabbitMQ 版本不支持
  • 需要启用相关插件

解决方案

bash
# 检查 RabbitMQ 版本(需要 3.7+)
rabbitmqctl version

# 正确设置限制
rabbitmqctl set_vhost_limits -p /vhost_name '{"max-queues": 100}'

# 查看限制
rabbitmqctl list_vhost_limits /vhost_name

# 清除并重新设置
rabbitmqctl clear_vhost_limits -p /vhost_name
rabbitmqctl set_vhost_limits -p /vhost_name '{"max-queues": 100, "max-connections": 50}'

最佳实践建议

1. 命名规范

推荐命名格式:

环境隔离:/{environment}
- /dev
- /test
- /prod

服务隔离:/svc_{service_name}
- /svc_order
- /svc_payment

租户隔离:/tenant_{tenant_id}
- /tenant_001
- /tenant_acme_corp

混合模式:/{env}_{service}
- /prod_order
- /test_payment

2. 资源限制建议

php
<?php

class VHostLimitPresets
{
    public const DEVELOPMENT = [
        'max_queues' => 50,
        'max_connections' => 20,
    ];

    public const TESTING = [
        'max_queues' => 100,
        'max_connections' => 50,
    ];

    public const STAGING = [
        'max_queues' => 200,
        'max_connections' => 100,
    ];

    public const PRODUCTION = [
        'max_queues' => 500,
        'max_connections' => 200,
    ];

    public const ENTERPRISE = [
        'max_queues' => 2000,
        'max_connections' => 1000,
    ];
}

3. 监控告警配置

php
<?php

class VHostAlertConfig
{
    public const ALERT_THRESHOLDS = [
        'queue_usage_warning' => 0.7,
        'queue_usage_critical' => 0.9,
        'connection_usage_warning' => 0.7,
        'connection_usage_critical' => 0.9,
        'message_backlog_warning' => 10000,
        'message_backlog_critical' => 100000,
    ];

    public static function checkThresholds(array $stats, array $limits): array
    {
        $alerts = [];
        
        if (!empty($limits['max-queues'])) {
            $usage = $stats['queues'] / $limits['max-queues'];
            if ($usage >= self::ALERT_THRESHOLDS['queue_usage_critical']) {
                $alerts[] = ['level' => 'critical', 'message' => '队列数量达到上限'];
            } elseif ($usage >= self::ALERT_THRESHOLDS['queue_usage_warning']) {
                $alerts[] = ['level' => 'warning', 'message' => '队列数量接近上限'];
            }
        }
        
        return $alerts;
    }
}

4. 自动化部署脚本

bash
#!/bin/bash
# deploy-vhosts.sh

VHOSTS=(
    "/development"
    "/testing"
    "/staging"
    "/production"
)

LIMITS=(
    "50:20"
    "100:50"
    "200:100"
    "500:200"
)

for i in "${!VHOSTS[@]}"; do
    vhost="${VHOSTS[$i]}"
    IFS=':' read -r queues connections <<< "${LIMITS[$i]}"
    
    echo "Creating vhost: $vhost"
    rabbitmqctl add_vhost "$vhost"
    
    echo "Setting limits for $vhost"
    rabbitmqctl set_vhost_limits -p "$vhost" "{\"max-queues\": $queues, \"max-connections\": $connections}"
    
    echo "Setting default permissions"
    rabbitmqctl set_permissions -p "$vhost" admin ".*" ".*" ".*"
done

echo "VHost deployment complete!"

相关链接