安装 http://www.rabbitmq.com/install-standalone-mac.html
安装python rabbitMQ module
1
2
3
4
5
6
7
|
pip install pika or easy_install pika or 源码 https: / / pypi.python.org / pypi / pika |
实现最简单的队列通信
send端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#!/usr/bin/env python import pika connection = pika.BlockingConnection(pika.ConnectionParameters( 'localhost' )) channel = connection.channel() #声明queue channel.queue_declare(queue = 'hello' ) #n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange. channel.basic_publish(exchange = '', routing_key = 'hello' , body = 'Hello World!' ) print ( " [x] Sent 'Hello World!'" ) connection.close() |
receive端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
#_*_coding:utf-8_*_ __author__ = 'Alex Li' import pika connection = pika.BlockingConnection(pika.ConnectionParameters( 'localhost' )) channel = connection.channel() #You may ask why we declare the queue again ‒ we have already declared it in our previous code. # We could avoid that if we were sure that the queue already exists. For example if send.py program #was run before. But we're not yet sure which program to run first. In such cases it's a good # practice to repeat declaring the queue in both programs. channel.queue_declare(queue = 'hello' ) def callback(ch, method, properties, body): print ( " [x] Received %r" % body) channel.basic_consume(callback, queue = 'hello' , no_ack = True ) print ( ' [*] Waiting for messages. To exit press CTRL+C' ) channel.start_consuming() |
远程连接rabbitmq server的话,需要配置权限 噢
首先在rabbitmq server上创建一个用户
1
|
sudo rabbitmqctl add_user alex alex3714 |
同时还要配置权限,允许从外面访问
1
|
sudo rabbitmqctl set_permissions -p / alex ".*" ".*" ".*" |
set_permissions [-p vhost] {user} {conf} {write} {read}
- vhost
-
The name of the virtual host to which to grant the user access, defaulting to /.
- user
-
The name of the user to grant access to the specified virtual host.
- conf
-
A regular expression matching resource names for which the user is granted configure permissions.
- write
-
A regular expression matching resource names for which the user is granted write permissions.
- read
-
A regular expression matching resource names for which the user is granted read permissions.
客户端连接的时候需要配置认证参数
1
2
3
4
5
6
|
credentials = pika.PlainCredentials( 'alex' , 'alex3714' ) connection = pika.BlockingConnection(pika.ConnectionParameters( '10.211.55.5' , 5672 , '/' ,credentials)) channel = connection.channel() |