部署环境:单机docker 部署方式:2个nameServer、2个Master、2个slave
操作步骤:
1、创建一个生产者,队列数量采用默认的4个,代码如下:
public static void main(String[] args) throws Exception { //Instantiate with a producer group name. DefaultMQProducer producer = new DefaultMQProducer("group_test"); // Specify name server addresses. producer.setNamesrvAddr("192.168.1.6:9876:192.168.1.6:9877"); //Launch the instance. producer.start(); int i = 0; while (true) { //Create a message instance, specifying topic, tag and message body. Message msg = new Message("TopicTestL" /* Topic /, "TagA" / Tag /, ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET) / Message body */ ); //Call send message to deliver message to one of brokers. SendResult sendResult = producer.send(msg); System.out.printf("%s%n", sendResult); Thread.sleep(1000); } //Shut down once the producer instance is not longer in use. //producer.shutdown(); }
2、创建两个消费者,代码如下:
private static void consume(String instanceName) throws MQClientException { // Instantiate with specified consumer group name. DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group_test"); // Specify name server addresses. consumer.setNamesrvAddr("192.168.1.6:9876:192.168.1.6:9877"); consumer.setInstanceName(instanceName); // Subscribe one more more topics to consume. consumer.subscribe("TopicTestL", "*"); consumer.setConsumerGroup("group_test"); // Register callback to execute on arrival of messages fetched from brokers. consumer.registerMessageListener(new MessageListenerConcurrently() { @Override public ConsumeConcurrentlyStatus consumeMessage(List msgs, ConsumeConcurrentlyContext context) { for (MessageExt m: msgs) { System.out.println("consume:" + instanceName + ",QueueId:" + m.getQueueId()); } return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } }); //Launch the consumer instance. consumer.start(); System.out.printf("Consumer Started.%n"); }
两个消费者分别从不同的进程或者线程启动,看到打印的消费记录如下:
consume:consume1,QueueId:0 consume:consume1,QueueId:1 consume:consume1,QueueId:2 consume:consume1,QueueId:3 consume:consume2,QueueId:0 consume:consume2,QueueId:1 consume:consume2,QueueId:2 consume:consume2,QueueId:3
问题:为什么每个消费者会消费到每个队列,或者说为什么一个消息队列会被多个消费者消费。(注意:消息本身是没有被重复消费),我期望的是每个消费者只消费一部分队列,每个消费队列一段时间只被一个消费者消费,是否我操作有误,还是设计如此?求解答,谢谢。
原提问者GitHub用户brucevoin
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
阿里云拥有国内全面的云原生产品技术以及大规模的云原生应用实践,通过全面容器化、核心技术互联网化、应用 Serverless 化三大范式,助力制造业企业高效上云,实现系统稳定、应用敏捷智能。拥抱云原生,让创新无处不在。