fanout消息订阅模式

  • 生产者

    # 生产者代码
    import pika credentials = pika.PlainCredentials('guest', 'guest') # mq用户名和密码
    # 虚拟队列需要指定参数 virtual_host,如果是默认的可以不填。
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1',
    credentials=credentials))
    # 建立rabbit协议的通道
    channel = connection.channel()
    # fanout: 所有绑定到此exchange的queue都可以接收消息(实时广播)
    # direct: 通过routingKey和exchange决定的那一组的queue可以接收消息(有选择接受)
    # topic: 所有符合routingKey(此时可以是一个表达式)的routingKey所bind的queue可以接收消息(更细致的过滤)
    channel.exchange_declare('logs', exchange_type='fanout') #因为是fanout广播类型的exchange,这里无需指定routing_key
    for i in range(10):
    channel.basic_publish(exchange='logs',
    routing_key='',
    body='Hello world!%s' % i) # 关闭与rabbitmq server的连接
    connection.close()
  • 消费者

    import pika
    
    credentials = pika.PlainCredentials('guest', 'guest')
    # BlockingConnection:同步模式
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1',
    credentials=credentials))
    channel = connection.channel() #作为好的习惯,在producer和consumer中分别声明一次以保证所要使用的exchange存在
    channel.exchange_declare(exchange='logs',
    exchange_type='fanout') # 随机生成一个新的空的queue,将exclusive置为True,这样在consumer从RabbitMQ断开后会删除该queue
    # 是排他的。
    result = channel.queue_declare('', exclusive=True) # 用于获取临时queue的name
    queue_name = result.method.queue # exchange与queue之间的关系成为binding
    # binding告诉exchange将message发送该哪些queue
    channel.queue_bind(exchange='logs',
    queue=queue_name) # 定义一个回调函数来处理消息队列中的消息,这里是打印出来
    def callback(ch, method, properties, body):
    # 手动发送确认消息
    print(body.decode())
    # 告诉生产者,消费者已收到消息
    #ch.basic_ack(delivery_tag=method.delivery_tag) # 如果该消费者的channel上未确认的消息数达到了prefetch_count数,则不向该消费者发送消息
    channel.basic_qos(prefetch_count=1)
    # 告诉rabbitmq,用callback来接收消息
    # 默认情况下是要对消息进行确认的,以防止消息丢失。
    # 此处将no_ack明确指明为True,不对消息进行确认。
    channel.basic_consume(queue=queue_name,
    on_message_callback=callback,
    auto_ack=True) # 自动发送确认消息
    # 开始接收信息,并进入阻塞状态,队列里有信息才会调用callback进行处理
    channel.start_consuming()

rabbitmq延迟队列

  • MQ类

    """
    Created on Fri Aug 3 17:00:44 2018 """
    import pika,json,logging
    class RabbitMQClient:
    def __init__(self, conn_str='amqp://guest:guest@127.0.0.1/%2f'):
    self.exchange_type = "direct"
    self.connection_string = conn_str
    self.connection = pika.BlockingConnection(pika.URLParameters(self.connection_string))
    self.channel = self.connection.channel()
    self._declare_retry_queue() #RetryQueue and RetryExchange
    logging.debug("connection established")
    def close_connection(self):
    self.connection.close()
    logging.debug("connection closed")
    def declare_exchange(self, exchange):
    self.channel.exchange_declare(exchange=exchange,
    exchange_type=self.exchange_type,
    durable=True)
    def declare_queue(self, queue):
    self.channel.queue_declare(queue=queue,
    durable=True,)
    def declare_delay_queue(self, queue,DLX='RetryExchange',TTL=60000):
    """
    创建延迟队列
    :param TTL: ttl的单位是us,ttl=60000 表示 60s
    :param queue:
    :param DLX:死信转发的exchange
    :return:
    """
    arguments={}
    if DLX:
    #设置死信转发的exchange
    arguments[ 'x-dead-letter-exchange']=DLX
    if TTL:
    arguments['x-message-ttl']=TTL
    print(arguments)
    self.channel.queue_declare(queue=queue,
    durable=True,
    arguments=arguments)
    def _declare_retry_queue(self):
    """
    创建异常交换器和队列,用于存放没有正常处理的消息。
    :return:
    """
    self.channel.exchange_declare(exchange='RetryExchange',
    exchange_type='fanout',
    durable=True)
    self.channel.queue_declare(queue='RetryQueue',
    durable=True)
    self.channel.queue_bind('RetryQueue', 'RetryExchange','RetryQueue')
    def publish_message(self,routing_key, msg,exchange='',delay=0,TTL=None):
    """
    发送消息到指定的交换器
    :param exchange: RabbitMQ交换器
    :param msg: 消息实体,是一个序列化的JSON字符串
    :return:
    """
    if delay==0:
    self.declare_queue(routing_key)
    else:
    self.declare_delay_queue(routing_key,TTL=TTL)
    if exchange!='':
    self.declare_exchange(exchange)
    self.channel.basic_publish(exchange=exchange,
    routing_key=routing_key,
    body=msg,
    properties=pika.BasicProperties(
    delivery_mode=2,
    type=exchange
    ))
    self.close_connection()
    print("message send out to %s" % exchange)
    logging.debug("message send out to %s" % exchange)
    def start_consume(self,callback,queue='#',delay=1):
    """
    启动消费者,开始消费RabbitMQ中的消息
    :return:
    """
    if delay==1:
    queue='RetryQueue'
    else:
    self.declare_queue(queue)
    self.channel.basic_qos(prefetch_count=1)
    try:
    self.channel.basic_consume( # 消费消息
    queue, # 你要从那个队列里收消息
    callback, # 如果收到消息,就调用callback函数来处理消息
    )
    self.channel.start_consuming()
    except KeyboardInterrupt:
    self.stop_consuming()
    def stop_consuming(self):
    self.channel.stop_consuming()
    self.close_connection()
    def message_handle_successfully(channel, method):
    """
    如果消息处理正常完成,必须调用此方法,
    否则RabbitMQ会认为消息处理不成功,重新将消息放回待执行队列中
    :param channel: 回调函数的channel参数
    :param method: 回调函数的method参数
    :return:
    """
    channel.basic_ack(delivery_tag=method.delivery_tag)
    def message_handle_failed(channel, method):
    """
    如果消息处理失败,应该调用此方法,会自动将消息放入异常队列
    :param channel: 回调函数的channel参数
    :param method: 回调函数的method参数
    :return:
    """
    channel.basic_reject(delivery_tag=method.delivery_tag, requeue=False)
  • 生产者

    from rabbitmq_demo import RabbitMQClient
    print("start program")
    client = RabbitMQClient()
    msg1 = '{"key":"10秒钟后执行"}'
    client.publish_message('test-delay',msg1,delay=1,TTL=10000)
    print("message send out")
  • 消费者

    from rabbitmq_demo import RabbitMQClient
    import json
    print("start program")
    client = RabbitMQClient()
    def callback(ch, method, properties, body):
    msg = body.decode()
    print(msg)
    # 如果处理成功,则调用此消息回复ack,表示消息成功处理完成。
    RabbitMQClient.message_handle_successfully(ch, method)
    queue_name = "RetryQueue"
    client.start_consume(callback,queue_name,delay=0)

RPC远程过程调用

  • 生产者

    # 生产者代码
    import pika
    import uuid # 在一个类中封装了connection建立、queue声明、consumer配置、回调函数等
    class FibonacciRpcClient(object):
    def __init__(self):
    # 建立到RabbitMQ Server的connection
    self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1', credentials=pika.PlainCredentials('guest', 'guest'))) self.channel = self.connection.channel() # 声明一个临时的回调队列
    result = self.channel.queue_declare('', exclusive=True)
    self._queue = result.method.queue # 此处client既是producer又是consumer,因此要配置consume参数
    # 这里的指明从client自己创建的临时队列中接收消息
    # 并使用on_response函数处理消息
    # 不对消息进行确认
    self.channel.basic_consume(queue=self._queue,
    on_message_callback=self.on_response,
    auto_ack=True)
    self.response = None
    self.corr_id = None # 定义回调函数
    # 比较类的corr_id属性与props中corr_id属性的值
    # 若相同则response属性为接收到的message
    def on_response(self, ch, method, props, body):
    print(body)
    if self.corr_id == props.correlation_id:
    print(body, '----')
    self.response = body def call(self, n):
    # 初始化response和corr_id属性
    self.corr_id = str(uuid.uuid4()) # 使用默认exchange向server中定义的rpc_queue发送消息
    # 在properties中指定replay_to属性和correlation_id属性用于告知远程server
    # correlation_id属性用于匹配request和response
    self.channel.basic_publish(exchange='',
    routing_key='rpc_queue',
    properties=pika.BasicProperties(
    reply_to=self._queue,
    correlation_id=self.corr_id,
    ),
    # message需为字符串
    body=str(n)) while self.response is None:
    self.connection.process_data_events() return int(self.response) # 生成类的实例
    fibonacci_rpc = FibonacciRpcClient() print(" [x] Requesting fib(30)")
    # 调用实例的call方法
    response = fibonacci_rpc.call(31)
    print(" [.] Got %r" % response)
  • 消费者

    # 消费者代码,这里以生成斐波那契数列为例
    import pika # 建立到达RabbitMQ Server的connection
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1', credentials=pika.PlainCredentials('guest', 'guest')))
    channel = connection.channel() # 声明一个名为rpc_queue的queue
    channel.queue_declare(queue='rpc_queue') # 计算指定数字的斐波那契数
    def fib(n):
    if n == 0:
    return 0
    elif n == 1:
    return 1
    else:
    return fib(n - 1) + fib(n - 2) # 回调函数,从queue接收到message后调用该函数进行处理
    def on_request(ch, method, props, body):
    # 由message获取要计算斐波那契数的数字
    n = int(body)
    print(" [.] fib(%s)" % n)
    # 调用fib函数获得计算结果 channel.basic_consume(queue='',
    on_message_callback=on_request,
    auto_ack=True) channel.start_consuming()

单生产者消费者模型

  • 生产者

    # 生产者代码
    import pika credentials = pika.PlainCredentials("guest","guest") # mq用户名和密码,没有则需要自己创建
    # 虚拟队列需要指定参数 virtual_host,如果是默认的可以不填。
    connection = pika.BlockingConnection(pika.ConnectionParameters(host="127.0.0.1",
    credentials=credentials)) # 建立rabbit协议的通道
    channel = connection.channel()
    # 声明消息队列,消息将在这个队列传递,如不存在,则创建。durable指定队列是否持久化
    channel.queue_declare(queue='python-test', durable=False) # message不能直接发送给queue,需经exchange到达queue,此处使用以空字符串标识的默认的exchange
    # 向队列插入数值 routing_key是队列名
    channel.basic_publish(exchange='',
    routing_key='python-test',
    body='Hello wo5555555')
    # 关闭与rabbitmq server的连接
    connection.close()
  • 消费者

    # 消费者代码
    import pika credentials = pika.PlainCredentials("guest","guest")
    # BlockingConnection:同步模式
    connection = pika.BlockingConnection(pika.ConnectionParameters(host="127.0.0.1",
    credentials=credentials))
    channel = connection.channel()
    # 申明消息队列。当不确定生产者和消费者哪个先启动时,可以两边重复声明消息队列。
    channel.queue_declare(queue='python-test', durable=False)
    # 定义一个回调函数来处理消息队列中的消息,这里是打印出来
    def callback(ch, method, properties, body):
    # 手动发送确认消息
    ch.basic_ack(delivery_tag=method.delivery_tag)
    print(body.decode())
    # 告诉生产者,消费者已收到消息 # 告诉rabbitmq,用callback来接收消息
    # 默认情况下是要对消息进行确认的,以防止消息丢失。
    # 此处将auto_ack明确指明为True,不对消息进行确认。
    channel.basic_consume('python-test',
    on_message_callback=callback)
    # auto_ack=True) # 自动发送确认消息
    # 开始接收信息,并进入阻塞状态,队列里有信息才会调用callback进行处理
    channel.start_consuming()

消息分发模型

  • 生产者

    # 生产者代码
    import pika credentials = pika.PlainCredentials('guest', 'guest') # mq用户名和密码
    # 虚拟队列需要指定参数 virtual_host,如果是默认的可以不填。
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1',
    credentials=credentials)) # 建立rabbit协议的通道
    channel = connection.channel()
    # 声明消息队列,消息将在这个队列传递,如不存在,则创建。durable指定队列是否持久化。确保没有确认的消息不会丢失
    channel.queue_declare(queue='rabbitmqtest', durable=True) # message不能直接发送给queue,需经exchange到达queue,此处使用以空字符串标识的默认的exchange
    # 向队列插入数值 routing_key是队列名
    # basic_publish的properties参数指定message的属性。此处delivery_mode=2指明message为持久的
    for i in range(10):
    print(i, "----")
    channel.basic_publish(exchange='',
    routing_key='rabbitmqtest',
    body='Hello world!%s' % i,
    properties=pika.BasicProperties(delivery_mode=2))
    # 关闭与rabbitmq server的连接
    connection.close()
  • 消费者

    # 消费者代码,consume1与consume2
    import pika
    import time credentials = pika.PlainCredentials('guest', 'guest')
    # BlockingConnection:同步模式
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1',
    credentials=credentials))
    channel = connection.channel()
    # 申明消息队列。当不确定生产者和消费者哪个先启动时,可以两边重复声明消息队列。
    channel.queue_declare(queue='rabbitmqtest', durable=True)
    # 定义一个回调函数来处理消息队列中的消息,这里是打印出来
    def callback(ch, method, properties, body):
    # 手动发送确认消息
    time.sleep(3)
    print(body.decode())
    # 告诉生产者,消费者已收到消息
    ch.basic_ack(delivery_tag=method.delivery_tag) # 如果该消费者的channel上未确认的消息数达到了prefetch_count数,则不向该消费者发送消息
    channel.basic_qos(prefetch_count=1)
    # 告诉rabbitmq,用callback来接收消息
    # 默认情况下是要对消息进行确认的,以防止消息丢失。
    # 此处将no_ack明确指明为True,不对消息进行确认。
    channel.basic_consume('rabbitmqtest',
    on_message_callback=callback,)
    # auto_ack=True) # 自动发送确认消息
    # 开始接收信息,并进入阻塞状态,队列里有信息才会调用callback进行处理
    channel.start_consuming()

Python RabbitMQ Demo的更多相关文章

  1. Python之路-python(rabbitmq、redis)

    一.RabbitMQ队列 安装python rabbitMQ module pip install pika or easy_install pika or 源码 https://pypi.pytho ...

  2. python RabbitMQ队列/redis

    RabbitMQ队列 rabbitMQ是消息队列:想想之前的我们学过队列queue:threading queue(线程queue,多个线程之间进行数据交互).进程queue(父进程与子进程进行交互或 ...

  3. python RabbitMQ队列使用(入门篇)

    ---恢复内容开始--- python RabbitMQ队列使用 关于python的queue介绍 关于python的队列,内置的有两种,一种是线程queue,另一种是进程queue,但是这两种que ...

  4. Python RabbitMQ消息队列

    python内的队列queue 线程 queue:不同线程交互,不能夸进程 进程 queue:只能用于父进程与子进程,或者同一父进程下的多个子进程,进行交互 注:不同的两个独立进程是不能交互的.   ...

  5. python RabbitMQ队列使用

    python RabbitMQ队列使用 关于python的queue介绍 关于python的队列,内置的有两种,一种是线程queue,另一种是进程queue,但是这两种queue都是只能在同一个进程下 ...

  6. python Rabbitmq编程(一)

    python Rabbitmq编程(一) 实现最简单的队列通信 send端 #!/usr/bin/env python import pika credentials = pika.PlainCred ...

  7. Python—RabbitMQ

    RabbitMQ RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统 安装 因为RabbitMQ由erlang实现,先安装erlang #安装配置epel源 rpm -ivh http ...

  8. python rabbitmq

    #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: zengchunyun ""& ...

  9. python supervisor demo deployment

    I did a demo about how to deploy other python apps served by a 'supervisord' daemon processor on git ...

  10. Python RabbitMQ消息持久化

    RabbitMQ消息持久化:就是将队列中的消息永久的存放在队列中.   处理方案: # 在实例化时加入durable=True来确认消息的实例化,客户端服务端都要写 channel.queue_dec ...

随机推荐

  1. Git 07 IDEA基本使用

    IDEA 是目前最流行的 Java 集成开发环境,我们一般使用 Git 都是在 IDEA 上操作. 这里以 2021.3.2 版 IDEA 为例. 克隆项目 1.复制 Gitee 上的项目地址 2.点 ...

  2. 如何监控容器或K8s中的OpenSearch

    概述 当前 OpenSearch 使用的越来越多, 但是 OpenSearch 生态还不尽完善. 针对如下情况: 监控容器化或运行在 K8s 中的 OpenSearch 我查了下, 官方还没有提供完备 ...

  3. XRebel工具激活方式,亲测有效

    首先进入生成 GUID 的网址:https://www.guidgen.com/ 用这个网址 + 生成的 GUID 激活:https://jrebel.qekang.com/ 例如:https://j ...

  4. CS101

    Turing machine:图灵机 理论上可以计算任何东西 CPU(Center Process Unit):中央处理器 是现代电脑的"大脑",其中包含数十亿细小开关的硅片,即晶 ...

  5. Weblogic、Tomcat、Apache、Nginx等web容器学习笔记

    1.weblogic weblogic是美国Oracle公司的一款产品,是一个基于JAVAEE架构的中间件.是用于开发.集成.部署 .管理大型分布式Web应用.网络应用.数据库应用的Java应用服务器 ...

  6. iOS自动化打包命令xcodebuild大全

    iOS实现自动化打包已经稳定运营几年了,不同的场景用到xcodebuild命令不一样,有的参数可能一直都用不到,列举一些常用的命令,比如编译命令: xcodebuild archive -worksp ...

  7. marquee实现滚动

    marquee的基本语法:<marquee> ... </marquee> 参数:1.滚动方向 (direction):left(左).right(右).up(上).down( ...

  8. 力扣1077(MySQL)-项目员工Ⅲ(中等)

    题目: 写 一个 SQL 查询语句,报告在每一个项目中经验最丰富的雇员是谁.如果出现经验年数相同的情况,请报告所有具有最大经验年数的员工. 查询结果格式在以下示例中: employee_id 为 1 ...

  9. 力扣278(java&python)-第一个错误的版本(简单)

    题目: 你是产品经理,目前正在带领一个团队开发新的产品.不幸的是,你的产品的最新版本没有通过质量检测.由于每个版本都是基于之前的版本开发的,所以错误的版本之后的所有版本都是错的. 假设你有 n 个版本 ...

  10. 力扣396(java)-旋转数组(中等)

    题目: 给定一个长度为 n 的整数数组 nums . 假设 arrk 是数组 nums 顺时针旋转 k 个位置后的数组,我们定义 nums 的 旋转函数  F 为: F(k) = 0 * arrk[0 ...