Skip to content
Advertisement

is it possible to get the group name from registerMessageListener in RocketMQ

I am using RocketMQ as the message center, this is the consumer dependencies jar:

<dependency>
            <groupId>org.apache.rocketmq</groupId>
            <artifactId>rocketmq-client</artifactId>
            <version>4.9.1</version>
        </dependency>

this is part of the conumser code:

consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                for (MessageExt message : msgs) {
                    String params = new String(message.getBody(), StandardCharsets.UTF_8);
                    ObjectMapper mapper = new ObjectMapper();
                    try {
                        Map<String, Object> parameters = mapper.readValue(params, Map.class);
                        String messageTopic = context.getMessageQueue().getTopic();
                        // what should I do to get the group name ?
                    } catch (JsonProcessingException e) {
                        throw new RuntimeException(e);
                    }
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        consumer.start();

in this code block, I want to get the consumerGroup name, I tracing into the ConsumeConcurrentlyContext class and only found the topic, did not found the consumerGroup name. is it possible to get the consumerGroup name from the registerMessageListener block?

Advertisement

Answer

Actually you needn’t. Since you can already got the consumer group name in the callback method from your consumer instance by

consumer.getConsumerGroup().

Maybe you will need to define a non-anonymous instance for the listener.

You can try

public class MyMessageListenerConcurrently implements MessageListenerConcurrently{
    private String consumerGroupName;
    public MyMessageListenerConcurrently(String consumerGroupName) {
        this.consumerGroupName = consumerGroupName
    }
    ....
}

And when you register:

    consumer.registerMessageListener(new MyMessageListenerConcurrently(consumer.getConsumerGroup()));

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement