拿来即用-gitlab迁移https://blog.csdn.net/qq_29857207/article/details/132256530?spm=1001.2014.3001.5502上篇文章“拿来即用-gitlab迁移”中已经说了新时代下的运维体系的好处及gitlab的迁移过程。同样如此,RabbitMQ的迁移也少不了,今天分享RabbitMQ的python版迁移代码,拿来即用。
从传统服务器部署到k8s部署的迁移已经完成了,后面陆续分享迁移过程中的心得体会、技巧、如何避坑及实际用到的通用类代码,欢迎关注、点赞、转发!
废话不多,直接上代码。
安装依赖
1.系统中只有一个python版本时的安装方式
pip install pika requests
2.如果你使用的是 Python 3,并且系统中同时安装了 Python 2,你需要使用 pip3
来确保为 Python 3 安装库
pip3 install pika requests
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):
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']}")
for queue in queues:
target_channel.queue_declare(
queue=queue['name'],
durable=queue['durable'],
auto_delete=queue['auto_delete']
)
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()