本示例確保環境有 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()
發文不易,知識沉淀,記得關注哦