在Linux上配置RabbitMQ消息路由主要涉及安裝RabbitMQ、配置交換器、創建隊列、綁定隊列到交換器以及發送和接收消息等步驟。以下是詳細的配置流程:
安裝Erlang:
yum install erlang
。下載并安裝RabbitMQ:
yum install rabbitmq-server
。配置RabbitMQ:
/etc/rabbitmq/rabbitmq.config
,并設置相關配置,如監聽地址、端口等。RABBITMQ_MNESIA_BASE
和RABBITMQ_LOG_BASE
。啟用管理插件(可選):
rabbitmq-plugins enable rabbitmq_management
命令啟用管理插件,以便通過Web界面管理RabbitMQ。RabbitMQ支持多種消息路由模式,包括直連交換器(Direct)、扇形交換器(Fanout)、主題交換器(Topic)和標題交換器(Headers)。以下是每種模式的簡要說明和配置示例:
[
{rabbit, [
{direct_listeners, [
{5672, ["localhost"]}
]}
]}
].
[
{rabbit, [
{fanout_listeners, [
{5672, ["localhost"]}
]}
]}
].
[
{rabbit, [
{topic_listeners, [
{5672, ["localhost"]}
]}
]}
].
[
{rabbit, [
{headers_listeners, [
{5672, ["localhost"]}
]}
]}
].
發送消息:
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', 5672, 'guest', 'guest'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs', exchange_type='direct')
channel.basic_publish(exchange='direct_logs', routing_key='info', body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()
接收消息:
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', 5672, 'guest', 'guest'))
channel = connection.channel()
channel.queue_declare(queue='')
channel.queue_bind(exchange='', queue='', routing_key='')
def callback(ch, method, properties, body):
print(f" [x] Received {body}")
channel.basic_consume(queue='', on_message_callback=callback, auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
以上步驟和示例代碼展示了如何在Linux上配置RabbitMQ消息路由。請根據實際需求和環境調整配置。