分享

RabbitMQ消息队列

 心静水境 2018-03-19
#/usr/bin/env python
# -*- coding:utf-8 -*-

import pika
# credentials = pika.PlainCredentials('policymaker','policymaker')
# connection = pika.BlockingConnection(pika.ConnectionParameters(
# 'localhost',5672,'/',credentials))
# # ---------------------------------------------------------------------------------------
#
# def sender():
# connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
# channel = connection.channel()
# channel.queue_declare(queue='hello')
# channel.basic_publish(exchange='',
# routing_key='hello',
# body='Hello, World!')
# print('send msg: Hello World!')
# connection.close()
#
# def receiver():
# connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
# channel = connection.channel()
# channel.queue_declare(queue='hello')
# def callback(ch, method, properties, body):
# print('receive msg: %s' % body)
# ch.basic_ack(delivery_tag = method.delivery_tag) # 告诉生成者,消息处理完成
# channel.basic_consume(callback,
# queue='hello',
# no_ack=False)
# print('waiting for msg...')
# channel.start_consuming()
# receiver()
# sender()
# ---------------------------------------------------------------------------------------
class RabbitMQ(object):
def __init__(self,queue):
self.queue = queue # 队列名称
self.connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
self.channel = self.connection.channel()
self.channel.queue_declare(queue=self.queue)
def callbalk(self,ch,method,properties,body):
print(body)
ch.basic_ack(delivery_tag=method.delivery_tag) # 告诉生产者,消息处理完成
def sender(self):
self.channel.basic_publish(exchange='',routing_key='hello',body='hi') # routing_key:发送消息到的队列
self.connection.close()
def receiver(self):
self.channel.basic_consume(self.callbalk,queue=self.queue,no_ack=False)
print('wating...')
self.channel.start_consuming()


rabbitmq = RabbitMQ('helly')
rabbitmq.sender()
# rabbitmq.receiver()

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多