RabbitMQ : Can I get latest n messages?

4.6k Views Asked by At

I'm new on RabbitMQ.

I implemented websocket server with tyrus to get messages on real-time like Push Server with the book RabbitMQ essentials.

however, When I disconnected and reconnect, the server send all messages because I implemented like this.

consumer = new DefaultConsumer(channel)
{
    @Override
    public void handleDelivery(final String consumerTag,
                   final Envelope envelope,
                   final BasicProperties properties,
                   final byte[] body) throws IOException
    {
    handler.handleDelivery(channel, envelope, properties, body);
    }

};

So, I want to get 20 latest messages when users have requested(like scrolling), however, in honestly, I can't imagine how to implement it.

I want to implement these things.

  1. When a user connected to websocket server, then server sends latest 20 messages.

  2. When a user opened inbox layout and reached scroll bottom, then server sends next 20 messages.

  3. A new message for this user while has connected, then server send on real-time.

1

There are 1 best solutions below

2
kleash On BEST ANSWER

You need to use prefetch count to limit consuming of unacknowledged messages at your consumer startup.

You can use basicQos method on your channel. From RabbitMQ docs:

Channel channel = ...;
Consumer consumer = ...;
channel.basicQos(20); // Per consumer limit
channel.basicConsume("my-queue", false, consumer);

Refer RabbitMQ docs for more detail: http://www.rabbitmq.com/consumer-prefetch.html