Fork me on GitHub
余鸢

RabbitMQ

在Ubuntu服务器上安装RabbitMQ

在实际安装RabbitMQ之前的一个快速注释:Ubuntu 14.04的Erlang包有问题,如果你使用SSL与RabbitMQ,需要安装一个比Ubuntu包维护者提供的更新的版本,所以使用二进制https://www.erlang-solutions.com/resources/download.html,适用于Erlang 17.0或更高版本。

将RabbitMQ添加到软件包存储库列表:

1
2
echo 'deb http://www.rabbitmq.com/debian/ testing main' |
sudo tee /etc/apt/sources.list.d/rabbitmq.list

然后添加签名密钥:

1
2
wget -O- https://www.rabbitmq.com/rabbitmq-release-signing-key.asc |
sudo apt-key add -

更新和安装:

1
sudo apt-get update && sudo apt-get install rabbitmq-server

RabbitMQ’Hello World’

创建producer,发送两个消息到队列,消费者接收来自该队列的所有消息。

producer.py的代码(使用pika 0.10.0 Python客户端):

1
2
3
4
5
6
7
8
9
10
11
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='queueName')
channel.basic_publish(exchange='', routing_key='queueName', body='Hello')
channel.basic_publish(exchange='', routing_key='queueName', body='World!')
print("Message sent")
connection.close()

consumer.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='queueName')
def callback(ch, method, properties, body):
print("Received message: %r" % body);
channel.basic_consume(callback, queue='queueName', no_ack=True)
print('Waiting for messages...')
channel.start_consuming()

输出为:

1
2
3
4
$ python receive.py
Waiting for messages...
Received message: 'Hello'
Received message: 'World!'

其他示例在其他语言的RabbitMQ教程页面中提供。