#!/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()
|