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. 什么是慢SQL且如何查看慢SQL

    什么是慢 SQL 且如何查看慢 SQL? 介绍 某个 SQL 执行时间超过指定时间时称为慢 SQL.我们可以查看慢 SQL,包括历史慢 SQL 以及当前慢 SQL. 查看历史慢 SQL 首先要设置 l ...

  2. 动态规划(六)——树形dp

    树形dp,又称树状dp,即在树上进行的dp,在设计动态规划算法时,一般就以节点从深到浅(子树从小到大)的顺序作为dp的"阶段",dp的状态表示中,第一维通常是节点编号(代表以该节点 ...

  3. c# 前台和后台线程

    前台和后台线程 Net的公用语言运行时(Common Language Runtime,CLR)能区分两种不同类型的线程:前台线程和后台线程.这两者的区别就是:应用程序必须运行完所有的前台线程才可以退 ...

  4. Flutter开发技巧集锦

    flutter中单例的写法 class AccountManager { factory AccountManager() => _instance ??= AccountManager._() ...

  5. 力扣436(java&python)-寻找右区间(中等)

    题目: 给你一个区间数组 intervals ,其中 intervals[i] = [starti, endi] ,且每个 starti 都 不同 . 区间 i 的 右侧区间 可以记作区间 j ,并满 ...

  6. [ABC342D] Square Pair 题解

    [题目描述] 给定一个长度为 \(N\) 的非负整数序列 \(A=\left(A_1,\cdots,A_n\right)\).求满足以下条件的整数对 \(\left(i,j\right)\) 的数量. ...

  7. 千万商家的智能决策引擎--AnalyticDB如何助力生意参谋双十一

    作者:算法&健兮,阿里巴巴数据技术及产品部技术专家 生意参谋介绍 生意参谋是阿里官方打造的全渠道.全链路.一站式数据平台,致力于为用户提供经营分析.市场洞察.客群洞察等多样化数据服务,帮助用户 ...

  8. 简单、有效、全面的Kubernetes监控方案

    ​简介:近年来,Kubernetes作为众多公司云原生改造的首选容器化编排平台,越来越多的开发和运维工作都围绕Kubernetes展开,保证Kubernetes的稳定性和可用性是最基础的需求,而这其中 ...

  9. 函数计算GB镜像秒级启动:下一代软硬件架构协同优化揭秘

    简介: 优化镜像加速冷启动大致分为两种做法:降低绝对延迟和降低冷启动概率.自容器镜像上线以来我们已经通过镜像加速技术,分阶段降低了绝对延迟.本文在此基础上,介绍借助函数计算下一代IaaS底座神龙裸金属 ...

  10. 前沿分享|阿里云数据库资深技术专家 姚奕玮:AnalyticDB MySQL离在线一体化技术揭秘

    ​简介: 本篇内容为2021云栖大会-云原生数据仓库AnalyticDB技术与实践峰会分论坛中,阿里云数据库资深技术专家 姚奕玮关于"AnalyticDB MySQL离在线一体化技术揭秘&q ...