本示例确保环境有 mysql redis rabbitmq
如果启动缺少对应python模块,请自行安装下
![9a223ba1e665a59a4e17e4d85b85dfef.png](https://i-blog.csdnimg.cn/blog_migrate/0a35a19dd9fc91611e499c49bea5c0ca.jpeg)
send-rabbitmq.py
!/usr/bin/python# -*- coding: utf-8 -*-import os,sysimport MySQLdbimport pikaimport randomimport 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 bodyconnection.close()db.close();
receive-rabbitmq.py
#!/usr/bin/env python3# -*- coding: utf-8 -*-import pikahostname = '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()
发文不易,知识沉淀,记得关注哦