RabbitMQ隊列

安裝 http://www.rabbitmq.com/install-standalone-mac.html

安裝python rabbitMQ module html

1
2
3
4
5
6
7
pip install pika
or
easy_install pika
or
源碼
  
https: / / pypi.python.org / pypi / pika

實現最簡單的隊列通訊python

 

send端express

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端bash

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的話,須要配置權限 噢 spa

首先在rabbitmq server上建立一個用戶code

1
sudo  rabbitmqctl  add_user alex alex3714  

同時還要配置權限,容許從外面訪問server

1
sudo  rabbitmqctl set_permissions -p / alex  ".*"  ".*"  ".*"

set_permissions [-p vhost] {user} {conf} {write} {read}htm

vhost

The name of the virtual host to which to grant the user access, defaulting to /.blog

user

The name of the user to grant access to the specified virtual host.rabbitmq

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()
相關文章
相關標籤/搜索