Skip to content
Daniel Blankensteiner edited this page Sep 16, 2019 · 3 revisions

Reader

A reader is actually just a consumer without a cursor. This means that Pulsar doesn't keep track of your progress and there is no need to acknowledge messages.

Creating a reader

Start with creating a client.

When creating a reader we have these options:

  • ReaderName - Set the reader name. This is optional.
  • MessagePrefetchCount - Number of messages that will be prefetched. Default is 1000.
  • ReadCompacted - Whether to read from the compacted topic. Default is false.
  • StartMessageId - The initial reader position is set to the specified message-id. This is required.
  • Topic - Set the topic for this reader. This is required.

Only the start message id and topic are required.

The class 'MessageId' has a public constructor and four properties: LedgerId, EntryId, Partition and BatchIndex. This enables you to save and create a MessageId and use it as the starting point for a reader (StartMessageId). If you want to start at the beginning of the topic, use the static MessageId.Earliest as StartMessageId. If you want to start at the end of the topic, use the static MessageId.Latest as StartMessageId.

Create a reader using the builder

var reader = client.NewReader()
                   .StartMessageId(MessageId.Earliest)
                   .Topic("persistent://public/default/mytopic")
                   .Create();

Create a reader without the builder

var readerOptions = new ReaderOptions
{
    StartMessageId = MessageId.Earliest,
    Topic = "persistent://public/default/mytopic"
};
var reader = client.CreateReader(readerOptions);

Receiving messages

Getting the next message from the topic is easy as:

var message = await reader.Receive();
Console.WriteLine("Received: " + Encoding.UTF8.GetString(message.Data.ToArray()));

Monitoring reader state

Monitoring the state is recommended and described here.

Disposing the reader

The Reader implements IDisposable and should be disposed when it's no longer needed. Disposing the client will dispose all readers.

Clone this wiki locally