在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消息路由。请根据实际需求和环境调整配置。