60 lines
2.2 KiB
Python
60 lines
2.2 KiB
Python
import asyncio
|
||
|
||
from product.direct_multi_publish import setup_multi_queue_balance, BalancedProducer
|
||
from product.direct_publish import setup_direct_exchange, direct_publish
|
||
from product.fanout_publish import fanout_publish, setup_fanout_exchange
|
||
from product.topic_publish import setup_topic_exchange, topic_publish
|
||
|
||
|
||
async def test_fanout_publish():
|
||
await setup_fanout_exchange("demo.fanout", "demo.fanout.queue-")
|
||
await fanout_publish(message="hello world", exchange_name="demo.fanout")
|
||
|
||
|
||
async def test_direct_exchange():
|
||
"""测试Direct交换器的消息发送"""
|
||
# 1. 初始化Direct交换器和队列绑定
|
||
await setup_direct_exchange()
|
||
|
||
# 2. 发送不同路由键的测试消息
|
||
test_messages = [
|
||
("系统崩溃,无法启动", "error"), # 路由到error队列
|
||
("磁盘空间不足", "warning"), # 路由到warning队列
|
||
("用户登录成功", "info"), # 路由到info队列
|
||
("调试信息:数据库连接成功", "debug") # 路由到info队列(因为info队列绑定了debug键)
|
||
]
|
||
|
||
for msg, routing_key in test_messages:
|
||
await direct_publish(msg, routing_key)
|
||
|
||
|
||
async def test_topic_exchange():
|
||
"""测试Topic交换器的通配符路由功能"""
|
||
# 1. 初始化Topic交换器和队列绑定
|
||
await setup_topic_exchange()
|
||
|
||
# 2. 发送不同路由键的测试消息(体现层级化路由)
|
||
test_messages = [
|
||
("订单创建失败(严重错误)", "order.create.critical"),
|
||
("用户登录成功", "user.login.success"),
|
||
("订单支付完成", "order.pay.success"),
|
||
("系统崩溃(严重错误)", "system.crash.critical"),
|
||
("用户登录失败", "user.login.failed"),
|
||
("普通系统日志", "system.log.info") # 不匹配任何绑定键,会被丢弃
|
||
]
|
||
|
||
for msg, routing_key in test_messages:
|
||
await topic_publish(msg, routing_key)
|
||
|
||
|
||
async def test_multi_queue_balance():
|
||
queue_count = 3
|
||
await setup_multi_queue_balance(queue_count=queue_count)
|
||
|
||
producer = BalancedProducer(queue_count=queue_count)
|
||
await producer.connect()
|
||
for i in range(10):
|
||
await producer.publish(f"任务{i + 1}:多队列负载均衡测试")
|
||
await asyncio.sleep(0.3)
|
||
await producer.close()
|