python消费rabbitmq
安装pika模块
pip install pika==0.13.1 # github https://github.com/pika/pika/ # 官网 https://pika.readthedocs.io/en/stable/
消费者脚本
# !/usr/bin/env python # -*- coding: utf-8 -*- # @time: 2021/1/28 9:39 下午 """ pip install pika==0.13.1 """ import sys import pika mq_host = '127.0.0.1' mq_vhost = '/' mq_queue_name = 'q_test_log' mq_username = 'test' mq_password = 'test123' def callback(ch, method, properties, body): # print(" [x] Received body %r" % body) body = body.decode('utf-8') try: print('消费数据 -> ', body) except Exception as e: print("error ->", e) ch.basic_ack(delivery_tag=method.delivery_tag) def main(): # print(' [*] Waiting for messages. To exit press CTRL+C') try: credentials = pika.PlainCredentials(mq_username, mq_password) connection = pika.BlockingConnection(pika.ConnectionParameters(mq_host, 5672, mq_vhost, credentials)) except Exception as e: print('连接mq失败', e) sys.exit(1) channel = connection.channel() channel.basic_qos(prefetch_count=1) channel.basic_consume(callback, queue=mq_queue_name) channel.start_consuming() if __name__ == '__main__': main()
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步