python、rabbitmq、pika、消息发送和接收实例

1. 下载Pika并安装

#mkdir -p /data/soft
#cd /data/soft
#wget https://pypi.python.org/packages/source/p/pip/pip-1.5.6.tar.gz#md5=01026f87978932060cc86c1dc527903e
#python setup.py install
Traceback (most recent call last):
  File "setup.py", line 6, in 
    from setuptools import setup
ImportError: No module named setuptools

如果第1步顺利没有报错可跳过2、3步,直接进入第4步


2. 安装setuptools

#yum install setuptool
#cd /data/soft
#wget http://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11-py2.7.egg
#sh setuptools-0.6c11-py2.7.egg 

3. 安装pika

#wget https://pypi.python.org/packages/source/p/pika/pika-0.9.14.tar.gz#md5=b99aad4b88961d3c7e4876b8327fc97c
#tar zxvf pika-0.9.14.tar.gz
#python setup.py install

4. 编写消息发送和接收实例(python版本之生产者/消息者)

最简单的示例,先尝试发送一个message给接受者
1) 生产/消费者   

send.py

#!/usr/bin/env python  
	import pika
	import random
	  
	credentials = pika.PlainCredentials('guest', 'geust')
	#这里可以连接远程IP,请记得打开远程端口  
	parameters = pika.ConnectionParameters('localhost',5672,'/',credentials)  
	connection = pika.BlockingConnection(parameters)  
	channel = connection.channel()  
	  
	#channel.queue_declare(queue='hello')  
	number = random.randint(1,1000)
	body = 'hello world:%s' %number
	channel.basic_publish(exchange='',  
	                      routing_key='hello',  
	                      body=body)  
	print " [x] Sent %s" %body  
	connection.close()  
receice.py

#!/usr/bin/env python  
	import pika  
	  
	credentials = pika.PlainCredentials('guest', 'nova')  
	parameters = pika.ConnectionParameters('localhost',5672,'/',credentials    )  
	connection = pika.BlockingConnection(parameters)  
	channel = connection.channel()  
	  
	channel.queue_declare(queue='hello')  
	  
	print ' [*] Waiting for messages. To exit press CTRL+C'  
	  
	def callback(ch, method, properties, body):  
	    print " [x] Received %r" % (body,)  
	  
	channel.basic_consume(callback,  
	                      queue='hello',  
	                      no_ack=True)  
	  
	channel.start_consuming()  

5. 测试实例send.py receice.py

# python one.py 
Traceback (most recent call last):
File "one.py", line 3, in 
import pika, sys
File "build/bdist.linux-i686/egg/pika/__init__.py", line 20, in 
File "build/bdist.linux-i686/egg/pika/adapters/__init__.py", line 23, in 
File "build/bdist.linux-i686/egg/pika/adapters/base_connection.py", line 9, in 
File "/usr/local/lib/python2.7/ssl.py", line 60, in 
import _ssl             # if we can't import it, let the error propagate
ImportError: No module named _ssl
解决方法:因为_ssl是python内置模块所以需要重新编译

# yum install openssl -y
# wget https://www.python.org/ftp/python/2.7.8/Python-2.7.8.tgz
# tar –zxvf Python-2.7.tgz
# cd Python-2.7
# ./configure
# make
# make install

6. 再次测试实例

开两个终端分别执行:receice.py  send.py


参数资料:http://blog.csdn.net/shatty/article/details/9529463

你可能感兴趣的:(python)