python RabbitMq的订阅

野生程序猿-杂烧4年前随意分享614

【test_RabbitMq1.py】

import pika
import json

credentials = pika.PlainCredentials('test', 'test')  # mq用户名和密码
connection = pika.BlockingConnection(pika.ConnectionParameters(host = '42.192.14.149',port = 5672,virtual_host = '/test',credentials = credentials))
channel=connection.channel()
# 声明exchange,由exchange指定消息在哪个队列传递,如不存在,则创建。durable = True 代表exchange持久化存储,False 非持久化存储
channel.exchange_declare(exchange = 'python-test',durable = True, exchange_type='fanout')
for i in range(2000):
    message=json.dumps({'OrderId':"1000%s"%i})
# 向队列插入数值 routing_key是队列名。delivery_mode = 2 声明消息在队列中持久化,delivery_mod = 1 消息非持久化。routing_key 不需要配置
    channel.basic_publish(exchange = 'python-test',routing_key = '',body = message,
                          properties=pika.BasicProperties(delivery_mode = 2))
    print(message)
connection.close()

【test_RabbitMq2.py】

import pika


credentials = pika.PlainCredentials('test', 'test')  # mq用户名和密码
connection = pika.BlockingConnection(pika.ConnectionParameters(host = '42.192.14.149',port = 5672,virtual_host = '/test',credentials = credentials))

channel = connection.channel()
# 创建临时队列,队列名传空字符,consumer关闭后,队列自动删除
result = channel.queue_declare('',exclusive=True)
# 声明exchange,由exchange指定消息在哪个队列传递,如不存在,则创建。durable = True 代表exchange持久化存储,False 非持久化存储
channel.exchange_declare(exchange = 'python-test',durable = True, exchange_type='fanout')
# 绑定exchange和队列  exchange 使我们能够确切地指定消息应该到哪个队列去
channel.queue_bind(exchange = 'python-test',queue = result.method.queue)
# 定义一个回调函数来处理消息队列中的消息,这里是打印出来
def callback(ch, method, properties, body):
    ch.basic_ack(delivery_tag = method.delivery_tag)
    print(body.decode())

channel.basic_consume(result.method.queue,callback,# 设置成 False,在调用callback函数时,未收到确认标识,消息会重回队列。True,无论调用callback成功与否,消息都被消费掉
                      auto_ack = False)
channel.start_consuming()


标签: RabbitMqpython

相关文章

python多数据库+memcache操作练习

import function import math import threading from pymemcache.client.base ...

编译的困扰-经验分享

编译的困扰-经验分享

开发的时候我们编译经常遇到坑,一会要用python3,一会又要用python 2.7的情况,nodejs一会要这个版本,一会要那个版本的情况,甚至npm都有版本要求。...

python小网站开发

看了前面讲的开发分段,开发小网站其实需要到的知识点不太多,有其他语言基础的基本可以直接上手。【views.py】""" 从module里 取方法,直接把数据提...

python操作mysql

根据php思路写的,最近有空的时候学一点python。# -*- coding: UTF-8 -*- import pymysql cla...