后续会持续分享人生感悟、工作技巧、技术原理、拿来即用的实用代码,欢迎关注、点赞、收藏!
一:迁移思路
1.1 迁移源RabbitMQ中的exchange到目标RabbitMQ
1.2 迁移源RabbitMQ中的queue到目标RabbitMQ
1.3 迁移源RabbitMQ中的绑定关系到目标RabbitMQ
二:实施
2.1 编程语言
python
2.2 安装依赖
2.2.1 系统中只有一个python版本时的依赖安装方式
pip install pika requests
2.2.2 系统中安装了多python版本的依赖安装方式
如果你使用的是 Python 3,并且系统中同时安装了 Python 2,你需要使用 pip3 来确保为 Python 3 安装库
pip3 install pika requests
2.3 python代码
import pika
import requests
from requests.auth import HTTPBasicAuth
# 配置源服务器(Server A)和目标服务器(Server B)的连接信息
source_server = {
'host': 'source-ip',
'port': 5672,
'user': 'user',
'password': 'pwd',
'api_port': 15672 # RabbitMQ HTTP API 端口,默认为15672
}
target_server = {
'host': 'target-ip',
'port': 5672,
'user': 'user',
'password': 'pwd',
'api_port': 15672
}
# 创建RabbitMQ管理API的基本URL
source_api_base_url = f"http://{source_server['host']}:{source_server['api_port']}/api"
target_api_base_url = f"http://{target_server['host']}:{target_server['api_port']}/api"
# 获取源服务器上的RabbitMQ配置信息
def get_rabbitmq_configuration(api_base_url, server_credentials):
auth = HTTPBasicAuth(server_credentials['user'], server_credentials['password'])
exchanges = requests.get(f"{api_base_url}/exchanges", auth=auth).json()
queues = requests.get(f"{api_base_url}/queues", auth=auth).json()
bindings = requests.get(f"{api_base_url}/bindings", auth=auth).json()
return exchanges, queues, bindings
# 在目标服务器上创建相同的RabbitMQ配置
def create_rabbitmq_configuration_on_target(target_channel, exchanges, queues, bindings):
# 迁移exchange
for exchange in exchanges:
if exchange['name'] and not exchange['name'].startswith('amq.'): # 忽略以 'amq.' 开头的交换机,amq.开头的交换机是RabbitMQ内置的交换机无需手动创建
target_channel.exchange_declare(
exchange=exchange['name'],
exchange_type=exchange['type'],
durable=exchange['durable'],
auto_delete=exchange['auto_delete']
)
else:
# 可以在这里打印日志或者处理试图声明保留交换机的情况
print(f"Skipping reserved exchange: {exchange['name']}")
# 迁移queue
for queue in queues:
target_channel.queue_declare(
queue=queue['name'],
durable=queue['durable'],
auto_delete=queue['auto_delete']
)
# 迁移binding
for binding in bindings:
if binding['source'] and binding['destination']: # 忽略没有source或destination的绑定
target_channel.queue_bind(
queue=binding['destination'],
exchange=binding['source'],
routing_key=binding['routing_key']
)
# 主函数
def main():
source_exchanges, source_queues, source_bindings = get_rabbitmq_configuration(source_api_base_url, source_server)
# 建立到目标服务器的连接
target_credentials = pika.PlainCredentials(target_server['user'], target_server['password'])
target_connection = pika.BlockingConnection(pika.ConnectionParameters(
host=target_server['host'],
port=target_server['port'],
credentials=target_credentials
))
target_channel = target_connection.channel()
# 创建目标服务器上的RabbitMQ配置
create_rabbitmq_configuration_on_target(target_channel, source_exchanges, source_queues, source_bindings)
# 关闭目标服务器的连接
target_connection.close()
if __name__ == "__main__":
main()
此专栏会分享在日常工作中遇到的具体问题的解决方案和拿来即用的代码,欢迎关注!