Home > OS >  How to read the messages from rabbitmq other than using listener configuration?
How to read the messages from rabbitmq other than using listener configuration?

Time:10-04

I am attempting to implement Spring Boot API to fetch the RabbitMQ Messages on demand for asynchronous cart notifications in UI. I already have a working implementation with the help of the Registered listener method. But I am looking for an alternative with or without spring.

@Component
public class Receiver {

  private CountDownLatch latch = new CountDownLatch(1);

  public void receiveMessage(String message) {
    System.out.println("Received <"   message   ">");
    latch.countDown();
  }

  public CountDownLatch getLatch() {
    return latch;
  }

}

Main Class with Reciever Configuration:

@SpringBootApplication
public class MessagingRabbitmqApplication {

  static final String topicExchangeName = "spring-boot-exchange";

  static final String queueName = "spring-boot";

  @Bean
  Queue queue() {
    return new Queue(queueName, false);
  }

  @Bean
  TopicExchange exchange() {
    return new TopicExchange(topicExchangeName);
  }

  @Bean
  Binding binding(Queue queue, TopicExchange exchange) {
    return BindingBuilder.bind(queue).to(exchange).with("foo.bar.#");
  }

  @Bean
  SimpleMessageListenerContainer container(ConnectionFactory connectionFactory,
      MessageListenerAdapter listenerAdapter) {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.setQueueNames(queueName);
    container.setMessageListener(listenerAdapter);
    return container;
  }

  @Bean
  MessageListenerAdapter listenerAdapter(Receiver receiver) {
    return new MessageListenerAdapter(receiver, "receiveMessage");
  }

  public static void main(String[] args) throws InterruptedException {
    SpringApplication.run(MessagingRabbitmqApplication.class, args).close();
  }

}

My Current Implementation Reference is from: https://spring.io/guides/gs/messaging-rabbitmq/

CodePudding user response:

See RabbitTemplate API:

/**
 * Receive a message if there is one from a specific queue. Returns immediately,
 * possibly with a null value.
 *
 * @param queueName the name of the queue to poll
 * @return a message or null if there is none waiting
 * @throws AmqpException if there is a problem
 */
@Nullable
Message receive(String queueName) throws AmqpException;


/**
 * Receive a message if there is one from a specific queue and convert it to a Java
 * object. Returns immediately, possibly with a null value.
 *
 * @param queueName the name of the queue to poll
 * @return a message or null if there is none waiting
 * @throws AmqpException if there is a problem
 */
@Nullable
Object receiveAndConvert(String queueName) throws AmqpException;

And respective docs: https://docs.spring.io/spring-amqp/reference/html/#polling-consumer

  • Related