Rocketmq的tag过滤和sql过滤

RocketMQ提供了两种消息过滤方式,包括基于Tag的过滤和符合SQL92标准的属性过滤。在使用属性过滤时,需开启enablePropertyFilter属性。本文将展示如何在Producer和Consumer中应用这些过滤机制。

    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");

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值