在大多数情况下,tag是一种简单而有用的设计,用于选择所需的信息。 例如:
1 |
|
2 |
|
消费者将收到包含TAGA或TAGB或TAGB的消息. 但限制是一条消息只能有一个标签,而这对于复杂的情况可能无效。 在这种情况下,您可以使用SQL表达式筛选出消息.
原理
SQL功能可以通过您在发送消息时放入的属性进行一些计算。 在RocketMQ定义的语法下,您可以实现一些有趣的逻辑。 这是一个例子:
------------ | message | |----------| a > 5 AND b = 'abc' | a = 10 | --------------------> Gotten | b = 'abc'| | c = true | ------------ ------------ | message | |----------| a > 5 AND b = 'abc' | a = 1 | --------------------> Missed | b = 'abc'| | c = true | ------------
语法
RocketMQ只定义了一些基本的语法来支持这个功能。 你也可以很容易地扩展它.
数字比较, 像
>
,>=
,<
,<=
,BETWEEN
,=
;字符比较, 像
=
,<>
,IN
;IS NULL
或者IS NOT NULL
;逻辑运算
AND
,OR
,NOT
;
常量类型是:
数字, 像123, 3.1415;
字符串, 像‘abc’,必须使用单引号;
NULL
, 特殊常数;布尔常量,
TRUE
或FALSE
;
使用限制
只有消费者可以通过SQL92选择消息。 示例:
1 | public void subscribe( final String topic, final MessageSelector messageSelector) |
生产者示例
发送时,您可以通过putUserProperty方法在消息中放置属性.
01 | DefaultMQProducer producer = new DefaultMQProducer( "please_rename_unique_group_name" ); |
02 | producer.start(); |
03 |
04 | Message msg = new Message( "TopicTest" , |
05 | tag, |
06 | ( "Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET) |
07 | ); |
08 | // Set some properties. |
09 | msg.putUserProperty( "a" , String.valueOf(i)); |
10 |
11 | SendResult sendResult = producer.send(msg); |
12 |
13 | producer.shutdown() |
消费者示例
消费时,使用Message Selector.by Sql通过SQL92选择消息.
01 | DefaultMQPushConsumer consumer = new DefaultMQPushConsumer( "please_rename_unique_group_name_4" ); |
02 |
03 | // only subsribe messages have property a, also a >=0 and a <= 3 |
04 | consumer.subscribe( "TopicTest" , MessageSelector.bySql( "a between 0 and 3" ); |
05 |
06 | consumer.registerMessageListener( new MessageListenerConcurrently() { |
07 | @Override |
08 | public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) { |
09 | return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; |
10 | } |
11 | }); |
12 |
|
(全文完)
阅读原文