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. 【开发者说】XstoryMaker快速书写剧本场景动画

    原文:https://mp.weixin.qq.com/s/63V0dfD2IufbX92JeD-G_A,点击链接查看更多技术内容. [开发者说]栏目是为HarmonyOS开发者提供的展示和分享平台, ...

  2. 编程小白也能快速掌握的ArkUI JS组件开发

    原文:https://mp.weixin.qq.com/s/ByxCMvtxaNuKI_6cXgtLBg,点击链接查看更多技术内容. Playground自上线以来,得到了广大开发者的一致好评.特别是 ...

  3. 重学c#系列——DiagnosticListener [三十五]

    前言 简单介绍一下DiagnosticListener,一个比较常见的事件通知模型,可以说是事件发布订阅模型,常用于监控. 正文 直接编写代码: using System.Diagnostics; p ...

  4. docker 应用篇————portainer[九]

    前言 简单介绍一下portainer. 正文 运行一下. docker run -d -p 8088:9000 --restart=always -v /var/run/docker.sock:/va ...

  5. linux 允许root 用户登录(旧)

    前言 旧博客迁移的内容 正文 vi /etc/ssh/sshd_config 将PermitRootLogin值改yes service sshd restart

  6. js 按照字母进行分组

    前言 js 按照字母进行分组的一个实例. 正文 var list = [ { 'name' : '张三', 'py' : 'zhnagsan' }, { 'name' : '李四', 'py' : ' ...

  7. 一种关于低代码平台(LCDP)建设实践与设计思路

    简介: 作者在负责菜鸟商业中心CRM系统开发过程中发现有一个痛点:业务线很多,每个业务线对同一个页面都有个性化布局和不同的字段需求,而他所在的团队就3个人,那么在资源有限的情况下该如何支撑呢?本文就降 ...

  8. 阿里 & 蚂蚁自研 IDE 研发框架 OpenSumi 正式开源

    ​简介:经历近 3 年时间,在阿里集团及蚂蚁集团共建小组的努力下,OpenSumi 作为国内首个强定制性.高性能,兼容 VS Code 插件体系的 IDE 研发框架,今天正式对外开源. ​ 作者 | ...

  9. WPF 给类库设置设计时使用的资源字典

    在开发 WPF 类库时,由于类库里面没有存在 App.xaml.cs 文件,而在对单个 XAML 进行开发时,设计器将会因为找不到资源文件的存在,而拿不到资源.本文告诉大家简单的方法,给设计器设置仅在 ...

  10. FFmpeg开发笔记(十七)Windows环境给FFmpeg集成字幕库libass

    ​libass是一个适用于ASS和SSA格式(Advanced Substation Alpha/Substation Alpha)的字幕渲染器,支持的字幕类型包括srt.ass等,凡是涉及到给视频画 ...