rocketmq支持两种方式的消息过滤。
1.tag过滤 (可以根据表达式来过滤tag)
consumer.subscribe("topic10", "*");
2.根据自定义属性进行过滤
consumer.subscribe("topic10", MessageSelector.bySql("age > 16"));
此时sql过滤遵循SQL92规范
注意:rocketmq默认是关闭了属性过滤,所以如果需要使用该功能,需要开启enablePropertyFilter的属性,将该属性置为true才可以。
使用示例:
producer
public class SyncProducer {
public static void main(String[] args) throws Exception{
//Instantiate with a producer group name
DefaultMQProducer producer = new DefaultMQProducer("producer_group_01");
//Specify name server addresses
producer.setNamesrvAddr("localhost:9876");
//Launch the instance
producer.start();
//Create a message instance, specifying topic, tag and message body.
Message msg = new Message("topic10",
"TagA",
("Hello RocketMQ ").getBytes(RemotingHelper.DEFAULT_CHARSET));
//set user property
msg.putUserProperty("name", "zhangsan");
msg.putUserProperty("age", "18");
//Call send message to deliver message to one of brokers.
SendResult sendResult = producer.send(msg);
System.out.printf("%s%n", sendResult);
//Shut down once the producer instance is not longer in use.
producer.shutdown();
}
}
consumer
public class Consumer {
public static void main(String[] args) throws Exception{
//Instantiate with specified consumer group name.
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer_group_01");
//Specify name server addresses.
consumer.setNamesrvAddr("localhost:9876");
//Subscribe one more more topics to consume.
// consumer.subscribe("topic10", "*");
consumer.subscribe("topic10", MessageSelector.bySql("age > 16"));
//Register callback to execute on arrival of messages fetched from brokers.
consumer.registerMessageListener(new MessageListenerConcurrently() {
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), list);
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
//Launch the consumer instance.
consumer.start();
System.out.printf("Consumer Started. %n");
}
}
RocketMQ提供了两种消息过滤方式,包括基于Tag的过滤和符合SQL92标准的属性过滤。在使用属性过滤时,需开启enablePropertyFilter属性。本文将展示如何在Producer和Consumer中应用这些过滤机制。
1791

被折叠的 条评论
为什么被折叠?



