创建 RabbitMQ 规则

创建 RabbitMQ 规则

  1. 搭建 RabbitMQ 环境,以 MaxOS X 为例:
$ brew install rabbitmq

 启动 rabbitmq
$ rabbitmq-server
  1. 创建规则:

打开 emqx dashboard 创建 RabbitMQ 规则 - 图1 (opens new window) ,选择左侧的 “规则” 选项卡。

选择触发事件 “消息发布”,然后填写规则 SQL:

``` SELECT * FROM "message.publish" WHERE topic =~ 't/#'

> 
> ![image](https://static.bookstack.cn/projects/emqx-enterprise-3.0-zh/46717c8111fde5058651580bdee7d355.png) 

  1. 关联动作:

> 在 “响应动作” 界面选择 “添加”,然后在 “动作” 下拉框里选择 “桥接数据到 RabbitMQ”。
> 
> ![image](https://static.bookstack.cn/projects/emqx-enterprise-3.0-zh/7aa2e74b25d67a8721eee4d9ab08fe89.png) 

  1. 填写动作参数:

> “桥接数据到 RabbitMQ 动作需要四个参数:
> 
> 1). RabbitMQ Exchange。这个例子里我们设置 Exchange 为 “messages”,
> 
> 2). RabbitMQ Exchange Type。这个例子我们设置 Exchange Type 为 “topic”
> 
> 3). RabbitMQ Routing Key。这个例子我们设置 Routing Key 为 “test”
> 
> 4). 关联资源。现在资源下拉框为空,可以点击右上角的 “新建资源” 来创建一个 RabbitMQ 资源:
> 
> ![image](https://static.bookstack.cn/projects/emqx-enterprise-3.0-zh/3fe75ec7697e9dadbe4aa3219392648e.png) 
> 
> 选择 RabbitMQ 资源。
> 
> ![image](https://static.bookstack.cn/projects/emqx-enterprise-3.0-zh/326c1cfa6492099963fcbd486f14612f.png) 

  1. 填写资源配置:

填写真实的 RabbitMQ 服务器地址,其他配置保持默认值,然后点击 “测试连接” 按钮,确保连接测试成功。

> 最后点击 “新建” 按钮。
> 
> ![image](https://static.bookstack.cn/projects/emqx-enterprise-3.0-zh/cf76731a552cb1ab4c2091564d7c0011.png) 

  1. 返回响应动作界面,点击 “确认”。

> ![image](https://static.bookstack.cn/projects/emqx-enterprise-3.0-zh/ee360d442ede2c9feaef2563ac1622bb.png) 

  1. 返回规则创建界面,点击 “新建”。

> ![image](https://static.bookstack.cn/projects/emqx-enterprise-3.0-zh/f1b4da2843422ae110fd4d197c4f53f0.png) 

  1. 规则已经创建完成,现在发一条数据:

> Topic: “t/1”
> 
> QoS: 0
> 
> Retained: false
> 
> Payload: “Hello, World!”
> 
> 编写 amqp 协议的客户端,以下是用 python 写的 amqp 客户端的示例代码:
> 
> ```
#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='messages', exchange_type='topic')

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

channel.queue_bind(exchange='messages', queue=queue_name, routing_key='test')

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

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

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

channel.start_consuming()

然后通过 amqp 协议的客户端查看消息是否发布成功, 以下是

image

在规则列表里,可以看到刚才创建的规则的命中次数已经增加了 1:

image