How to listen to multiple queues with autowired Spring Boot?

我与影子孤独终老i 提交于 2019-12-05 08:59:49

Ok, I figured out how to get it to listen to multiple queues. Think there might be some downsides compared to my other solution, mainly that it doesn't work if the queue listed does not exist. I ended up using a totally different approach using a @RabbitListener

@Component
public class EventListener {

    private static Logger LOG = LoggerFactory.getLogger(EventListener.class);
    private CountDownLatch latch = new CountDownLatch(1);

    @RabbitListener(queues = "myqueue")
    public void processPaymentMessage(Object message) {
        LOG.info("Message is of type: " + message.getClass().getName());
        if(!(message instanceof byte[])) message = ((Message) message).getBody();
        String content = new String((byte[])message, StandardCharsets.UTF_8);
        LOG.info("Received on myqueue: " + content);
        latch.countDown();
    }

    @RabbitListener(queues = "myotherqueue")
    public void processOrderMessage(Object message) {
        LOG.info("Message is of type: " + message.getClass().getName());
        if(!(message instanceof byte[])) message = ((Message) message).getBody();
        String content = new String((byte[])message, StandardCharsets.UTF_8);           
        LOG.info("Received on myotherqueue: " + content);
        latch.countDown();
    }   
}

The whole check on byte[] is in there because that what a message send from the commandline looks like. Otherwise it's a org.springframework.amqp.core.Message.

You can try this

In application.properties

rabbitmq.queue.names= com.queue1,com.queue2

In Java file

@RabbitListener(queues = "#{'${rabbitmq.queue.names}'.split(',')}")
public void receiveMessage(Message message) {
    try {
        if (processmessage(message)); 
        }
    } catch (Exception ex) {
        LOGGER.error("Exception while processing the Message", ex);
    }

}

Here's what worked for me in groovy:

@Component
@EnableRabbit
@Slf4j
class StatusListener {
    Library library
    int messageCounter

    @Autowired
    StatusListener(Library library) {
        this.library = library
    }

    @RabbitListener(queues = '#{library.allStatusQueues.split(",")}')
    void receiveMessage(Message message) {
        messageCounter++
        log.info("Rabbit Listener received message <" + new String(message.body) + "> (" + messageCounter + ")")
    }
}

Where Library is a configuration bean:

@Component
@ConfigurationProperties
@RefreshScope
class Library {
    String allStatusQueues
}

The property itself, in application.properties or similar config file looks like:

all-status-queues=queue1,queue2,queue3,queue4
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!