python3 实现rabbitmq exchange topic类型

1 生产者 python 实现

# -*- coding: utf-8 -*-

    import pika
    
    hostname = 'localhost'
    port = 5672
    username = 'yangzhen'
    password = '123456'
    
    credentials = pika.PlainCredentials(username=username, password=password)
    parameters = pika.ConnectionParameters(host=hostname,port=port,credentials=credentials)
    connection = pika.BlockingConnection(parameters=parameters)#创建连接
    
    channel = connection.channel()
    
    #创建模糊匹配的exchange
    channel.exchange_declare(exchange='topic_logs', exchange_type='topic')
    
    #这里关键字必须为点号隔开的单词,以便于消费者进行匹配。
    routing_key = '[warn].kern'
    
    message = 'Hello World!'
    channel.basic_publish(exchange='topic_logs', routing_key=routing_key, body=message)
    
    print('[生产者] Send %r:%r' % (routing_key, message))
    connection.close()

2 消费者python实现

# -*- coding: utf-8 -*-
import pika
import sys

hostname = 'localhost'
port = 5672
username = 'yangzhen'
password = '123456'

credentials = pika.PlainCredentials(username=username, password=password)
parameters = pika.ConnectionParameters(host=hostname,port=port,credentials=credentials)
connection = pika.BlockingConnection(parameters=parameters)#创建连接

channel = connection.channel()
channel.exchange_declare(exchange='topic_logs', exchange_type='topic')

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

#绑定键。‘#’匹配所有字符,‘*’匹配一个单词
binding_keys = ['[warn].*', 'info.*']

if not binding_keys:
    sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0])
    sys.exit(1)

for binding_key in binding_keys:
    channel.queue_bind(exchange='topic_logs', queue=queue_name, routing_key=binding_key)

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

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

channel.basic_consume(callback, queue=queue_name, no_ack=False)

channel.start_consuming()

3 从 web 界面观察

3.1. 生产者运行如下命令
[root@yangzhen rabbitmq]# watch -n 1 py3 send_topic.py
3.2. 消费者运行如下命令
[root@yangzhen rabbitmq]# py3 receive_topic.py
[*] Writing for logs. To exit press CTRL+C.
[x] ‘[warn].kern’:b’Hello World!’
[x] ‘[warn].kern’:b’Hello World!’
[x] ‘[warn].kern’:b’Hello World!’
3.3. 界面观察
python3 实现rabbitmq exchange topic类型_第1张图片
可以看到 exchange 有消息传递。
参考文章:https://www.cnblogs.com/wt11/p/5970297.html

你可能感兴趣的:(rabbitmq)