-
Notifications
You must be signed in to change notification settings - Fork 64
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.
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.
var reader = client.NewReader()
.StartMessageId(MessageId.Earliest)
.Topic("persistent://public/default/mytopic")
.Create();
var readerOptions = new ReaderOptions
{
StartMessageId = MessageId.Earliest,
Topic = "persistent://public/default/mytopic"
};
var reader = client.CreateReader(readerOptions);
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 the state is recommended and described here.
The Reader implements IDisposable and should be disposed when it's no longer needed. Disposing the client will dispose all readers.