本示例确保环境有 MySQL redis rabbitmq
如果启动缺少对应Python模块,请自行安装下
send-rabbitmq.py
!/usr/bin/python
# -*- coding: utf-8 -*-
import os,sys
import MySQLdb
import pika
import random
import redis
#安装模块 pip install pika
#数据库连接
db = MySQLdb.connect('localhsot','root','yumg10','xiaogezi',charset='utf8')
cursor = db.cursor()
cursor.execute("select order_no from t_Loan")
#redis连接
#pool=redis.ConnectionPool(decode_response=True)
redis=redis.Redis(host='localhost',password='123456',port=6379)
# 新建连接,rabbitmq安装在本地则hostname为'localhost'
hostname = 'localhsot'
parameters = pika.ConnectionParameters(hostname)
connection = pika.BlockingConnection(parameters)
# 创建通道
channel = connection.channel()
# 声明一个队列,生产者和消费者都要声明一个相同的队列,用来防止万一某一方挂了,另一方能正>常运行
channel.queue_declare(queue='hello')
for i in 'PYTHON AS YOU KNOW':
number = random.randint(1, 1000)
data=cursor.fetchone()
redis.set('data','a')
#print redis.get('data')
if data is None:
data=i
else:
data=data
body = 'hello world:%s' % data
# 交换机; 队列名,写明将消息发往哪个队列; 消息内容
# routing_key在使用匿名交换机的时候才需要指定,表示发送到哪个队列
channel.basic_publish(exchange='', routing_key='hello', body=body)
print body
connection.close()
db.close();
receive-rabbitmq.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pika
hostname = 'localhost'
parameters = pika.ConnectionParameters(hostname)
connection = pika.BlockingConnection(parameters)
# 创建通道
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print " [x] Received %r" % (body,)
# 告诉rabbitmq使用callback来接收信息
channel.basic_consume(callback, queue='hello', no_ack=True)
# 开始接收信息,并进入阻塞状态,队列里有信息才会调用callback进行处理,按ctrl+c退出
print ' [*] Waiting for messages. To exit press CTRL+C'
channel.start_consuming()
发文不易,知识沉淀,记得关注哦