rabbitMQ-python

消息队列 rabbitMQ

停止:rabbitmqctl stop
启动:rabbitmq-server start
添加用户
sudo rabbitmqctl add_user username password
删除用户
sudo rabbitmqctl delete_user username
修改密码
sudo rabbitmqctl change_password username newpassword

代码1

    #发送者:
    import pika

    # 建立一个实例
    connection = pika.BlockingConnection(
     pika.ConnectionParameters('localhost',5672) # 默认端口5672,可不写
     )
    # 声明一个管道,在管道里发消息
    channel = connection.channel()
    # 在管道里声明queue

    channel.queue_declare(queue='hello',durable=True)

    class ProducerMQ(object):
         def __init__(self):
             pass

         def __enter__(self):
             return self

         def __exit__(self, exc_type, exc_val, exc_tb):
             if not connection.is_closed:
             connection.close()

         def send(self,body):
         # RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
             channel.basic_publish(exchange='',
             routing_key='hello', # queue名字
             body=body,# 消息内容
             properties=pika.BasicProperties(
             delivery_mode=2# 消息持久化,在rabbitmq重启后队列及消息依然存在
                 )
             )
             print(" [x] Sent {}".format(body))

    if __name__ == '__main__':
         with ProducerMQ() as producer:
             [producer.send('hello {}'.format(i)) for i in range(10)]

    #消费者:
    import pika

    # 建立一个实例
    connection = pika.BlockingConnection(
     pika.ConnectionParameters('localhost',5672) # 默认端口5672,可不写
     )
    # 声明一个管道,在管道里发消息
    channel = connection.channel()
    # 在管道里声明queue

    channel.queue_declare(queue='hello',durable=True)


    class ConsumerMQ(object):
         def __init__(self):
             self.count=0

         def __enter__(self):
             return self

         def __exit__(self, exc_type, exc_val, exc_tb):
             if not connection.is_closed:
                 connection.close()

         def callback(self,ch, method, properties, body):

             if self.count>=5: #消费掉5个后退出
                 connection.close()
                 return
             print(" [x] Received %r{} {}" .format(self.count,body))
             ch.basic_ack(delivery_tag=method.delivery_tag)
             self.count+=1


         def receive(self):
         # RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
             channel.basic_consume(self.callback, queue='hello')
             print(' [*] Waiting for messages. To exit press CTRL+C')
             channel.start_consuming()

        if __name__ == '__main__':
             with ConsumerMQ() as consumer:
                 consumer.receive()

代码2

import pika
import time
import string
import json

host = '*.*.*.*'
username = '*'  # 指定远程rabbitmq的用户名
pwd = '*'  # 密码
queue_name = 'test'  # 队列名
user_pwd = pika.PlainCredentials(username, pwd)

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host=host, port=5672,
                              credentials=user_pwd))  # 创建连接

channel = connection.channel()  # 连接上创建一个频道

# durable 表示是否持久化,
# exclusive是否排他,如果为True则只允许创建这个队列的消费者使用,
# auto_delete 表示消费完是否删除队列
channel.queue_declare(queue=queue_name, durable=True, exclusive=False,
                      auto_delete=False)  # 声明一个队列,生产者和消费者都要声明一个相同的队列,用来防止万一某一方挂了,另一方能正常运行


# 生产者,发送消息
def send_message(data):
    # 需要将字典dumps成字符串
    channel.basic_publish(exchange='',  # 交换机
                          routing_key=queue_name,  # 路由键,写明将消息发往哪个队列,本例是将消息发往队列queue_name

                          body=json.dumps(data),  # 生产者要发送的消息
                          properties=pika.BasicProperties(
                              delivery_mode=2, )  # 设置消息持久化,将要发送的消息的属性标记为2,表示该消息要持久化)
                          )


# 消费者,接收消息
def receive_message():
    # prefetch_count设置为3,表示每次最多只取三个消息
    channel.basic_qos(prefetch_count=3)
    channel.basic_consume(callback, queue=queue_name)
    print(' [*] Waiting for messages. To exit press CTRL+C')
    try:
        channel.start_consuming()
    except KeyboardInterrupt:
        channel.close()
        connection.close()


def callback(ch, method, properties, body):
    result = handle_data(body)
    if result == 1:
        print(" [消费者] Done")
        ch.basic_ack(delivery_tag=method.delivery_tag)  # 接收到消息后会给rabbitmq发送一个确认
    else:
        print(" [x] handle data error")
        ch.basic_reject(delivery_tag=method.delivery_tag)


# 代写接口,处理下一步的数据
def handle_data(body):
    try:
        data = json.loads(body)
        print(" [消费者] Received {}".format(data))
        time.sleep(10)
    except:
        return 0
    else:
        return 1


if __name__ == '__main__':
    # send为True调用生产者,send为False调用消费者
    send = True
    # 发送数据
    if send:
        message = [{k: v} for k, v in enumerate(string.ascii_lowercase)]
        for m in message:
            print(m)
            send_message(data=m)

    # 接受数据
    else:
        receive_message()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值