首页 > 其他分享 >RBMQ案例四:路由模式

RBMQ案例四:路由模式

时间:2023-02-05 16:37:42浏览次数:32  
标签:pika RBMQ exchange direct queue 案例 channel 路由 name

 

 

使仅订阅消息的子集成为可能。例如,我们将能够仅将关键错误消息定向到日志文件(以节省磁盘空间),同时仍然能够在控制台上打印所有日志消息。   通过路由来匹配对应的消息

一、消息发布端

#!/usr/bin/env python
import pika
import sys
import json
import datetime


def get_message():
    # 产生消息入口处
    for i in range(100):  # 生成100条消息
        for str_t in ['info', 'warning', 'error']: # 生成三种类型的消息
            message = json.dumps({'id': "%s-90000%s" % (str_t, i), "amount": 100 * i, "name": "%s" % str_t,
                                  "createtime": str(datetime.datetime.now())})
            producer(message, str_t)


def producer(message, severity):
    # 登陆并创建信道
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(virtual_host='/melon_demo', host='82.156.19.94', port=5672,
                                  credentials=pika.PlainCredentials('guest', 'guest')))
    channel = connection.channel()

    channel.exchange_declare(exchange='direct_logs', exchange_type='direct', durable=True)
    channel.basic_publish(exchange='direct_logs', routing_key=severity, body=message)
    print(" [x] Sent %r:%r" % (severity, message))
    connection.close()


if __name__ == "__main__":
    get_message()  # 程序执行入口

二、接收所有的消息all

#!/usr/bin/env python
import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(virtual_host='/melon_demo', host='82.156.19.94', port=5672,
                              credentials=pika.PlainCredentials('guest', 'guest')))
channel = connection.channel()

channel.exchange_declare(exchange='direct_logs', exchange_type='direct',durable=True)

result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue


for severity in ['info','warning','error']:
    channel.queue_bind( exchange='direct_logs', queue=queue_name, routing_key=severity)

print(' [*] Waiting for all logs. To exit press CTRL+C')

def callback(ch, method, properties, body):
    print(" [x] %r:%r" % (method.routing_key, body))


channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)

channel.start_consuming()

三、接收所有的消息info

#!/usr/bin/env python
import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(virtual_host='/melon_demo', host='82.156.19.94', port=5672,
                              credentials=pika.PlainCredentials('guest', 'guest')))
channel = connection.channel()

channel.exchange_declare(exchange='direct_logs', exchange_type='direct',durable=True)

result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue


# for severity in ['info','warning','error']:
#     channel.queue_bind( exchange='direct_logs', queue=queue_name, routing_key=severity)
channel.queue_bind( exchange='direct_logs', queue=queue_name, routing_key='info')

print(' [*] Waiting for info. To exit press CTRL+C')

def callback(ch, method, properties, body):
    print(" [x] %r:%r" % (method.routing_key, body))


channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)

channel.start_consuming()

四、接收所有的消息error

#!/usr/bin/env python
import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(virtual_host='/melon_demo', host='82.156.19.94', port=5672,
                              credentials=pika.PlainCredentials('guest', 'guest')))
channel = connection.channel()

channel.exchange_declare(exchange='direct_logs', exchange_type='direct',durable=True)

result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue


channel.queue_bind( exchange='direct_logs', queue=queue_name, routing_key='error')

print(' [*] Waiting for error. To exit press CTRL+C')

def callback(ch, method, properties, body):
    print(" [x] %r:%r" % (method.routing_key, body))


channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)

channel.start_consuming()

五、接收消息warning

#!/usr/bin/env python
import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(virtual_host='/melon_demo', host='82.156.19.94', port=5672,
                              credentials=pika.PlainCredentials('guest', 'guest')))
channel = connection.channel()

channel.exchange_declare(exchange='direct_logs', exchange_type='direct',durable=True)

result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue


# for severity in ['info','warning','error']:
channel.queue_bind( exchange='direct_logs', queue=queue_name, routing_key='warning')

print(' [*] Waiting for warning. To exit press CTRL+C')

def callback(ch, method, properties, body):
    print(" [x] %r:%r" % (method.routing_key, body))


channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)

channel.start_consuming()

 

 

 

 

 

 

标签:pika,RBMQ,exchange,direct,queue,案例,channel,路由,name
From: https://www.cnblogs.com/1314520xh/p/17093521.html

相关文章

  • RBMQ案例五:主题模式
    在之前的教程中,我们改进了日志系统。我们没有使用只能进行虚拟广播的扇出交换器,而是使用了直接交换器,并获得了选择性接收日志的可能性。虽然使用直接交换改进了我们的系......
  • RBMQ案例三:发布/订阅模式
      在上篇教程中,我们搭建了一个工作队列,每个任务只分发给一个工作者(worker)。在本篇教程中,我们要做的跟之前完全不一样——分发一个消息给多个消费者(consumers)。这种......
  • RBMQ中python案例一:简单模式
    一、生产者与消费者模式之简单模式,原理图   二、生产者产生消息importjsonimportpikaimportdatetime#生产者producer.pydefget_message():#......
  • RBMQ案例二:工作队列模式
      工作队列模式工作队列(又名:任务队列)背后的主要思想是避免立即执行资源密集型任务而不得不等待它完成。相反,我们安排任务稍后完成。我们将任务封装为消息并将其发......
  • Spring2 - 入门案例
    Spring基本操作导入依赖在pom.xml中添加依赖添加依赖:<dependencies><!--springcontext依赖--><!--当你引入SpringContext依赖之后,表示将Spring的基础依......
  • 找了几个 Solon 的商业落地项目案例!
    Solon是啥?是一个高效的Java应用开发框架:更快、更小、更简单。(代码仓库:https://gitee.com/noear/solon)提倡:克制、简洁、开放、生态启动快5~10倍;qps高2~3倍;运......
  • Pandas 人口密度案例分析
    fromturtleimportleftimportpandasaspd"""需求:1.导入文件,查看原始数据2.将人口数据和各州简称数据进行合并3.将合并的数据中重复的abbreviation列进行删除......
  • TP-LINK 路由器密码加密方法
       functionorgAuthPwd(a){returnthis.securityEncode(a,"RDpbLfCPsJZ7fiv","yLwVl0zKqws7LgKPRQ84Mdt708T1qQ3Ha7xv3H7NyU84p21BriUWBU43odz3iP4rBL3cD......
  • 深入理解前端中的 hash 和 history 路由
    我们在使用Vue或者React等前端渲染时,通常会有hash路由和history路由两种路由方式。hash路由:监听url中hash的变化,然后渲染不同的内容,这种路由不向服务器发送......
  • 【八大数据排序法】快速排序法的图形理解和案例实现 | C++
    第十八章快速排序法:::hljs-center目录第十八章快速排序法●前言●认识排序●一、快速排序法是什么?1.简要介绍2.具体情况3.算法分析●二、案例实现1.......