title: How to get all existing messages from queue & stop consumer
body: <p>I want to get all awaiting messages from a queue &amp; then stop consumer. But it continues to wait for a new messages. I removed all unnecessary code:</p>
  
  <pre><code>public class Listener {
  
      private Channel channel;
  
      public Listener(boolean futureActionsAllowed) {
          this.futureActionsAllowed = futureActionsAllowed;
          channel = RabbitMQ.getChannel(TasksStatusOpts.QUEUE_NAME, TasksStatusOpts.DURABLE, TasksStatusOpts.EXCLUSIVE,
                  TasksStatusOpts.AUTO_DELETE);
      }
  
      public void getAndExit() throws IOException, InterruptedException {
          QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
          String consumerTag = channel.basicConsume(TasksStatusOpts.QUEUE_NAME, TasksStatusOpts.AUTO_ACK,
                  queueingConsumer);
          while (true) {
              QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
              if (delivery == null) {
                  channel.basicCancel(consumerTag);
                  Connection conn = channel.getConnection();
                  channel.close();
                  conn.close();
                  break;
              } else {
                  String message = new String(delivery.getBody(), Charsets.UTF_8);
                  handle(message, delivery.getEnvelope());
              }
          }
      }
  
      public static void main(String[] args) throws IOException {
          new Listener(false).getAndExit();
      }
  
  }
  </code></pre>