Skip to content

Producer

Daniel Blankensteiner edited this page Feb 21, 2021 · 3 revisions

Producer

Need to send a message to Pulsar? Well, that's why we have a producer.

Creating a producer

Start with creating a client.

When creating a producer we have these options:

  • ProducerName - Set the producer name. This is optional.
  • InitialSequenceId - Set the initial sequence id. The default is 0.
  • Topic - Set the topic for this producer. This is required.

Only the topic is required.

Create a producer using the builder

var producer = client.NewProducer()
                     .Topic("persistent://public/default/mytopic")
                     .Create();

Create a producer without the builder

var options = new ProducerOptions("persistent://public/default/mytopic");
var producer = client.CreateProducer(options);

Sending data

var data = Encoding.UTF8.GetBytes("Hello World");
await producer.Send(data);

Sending data with metadata

We have quite a few options in regards to metadata:

  • DeliverAt - Absolute timestamp indicating when the message should be delivered to consumers.
  • EventTime - Set the event time of the message.
  • Key - Set the key of the message for routing policy.
  • KeyBytes - Set the key of the message for routing policy.
  • OrderingKey - Set the ordering key of the message for message dispatch in SubscriptionType.KeyShared mode.
  • SequenceId - Set the sequence id of the message.

Besides these, we can also specify custom metadata. Let's see how.

Sending data with custom metadata using the builder

var data = Encoding.UTF8.GetBytes("Hello World");
var messageId = await producer.NewMessage()
                              .Property("SomeKey", "SomeValue")
                              .Send(data);

Sending data with custom metadata without the builder

var data = Encoding.UTF8.GetBytes("Hello World");
var metadata = new MessageMetadata();
metadata["SomeKey"] = "SomeValue";
var messageId = await producer.Send(metadata, data));

Monitoring producer state

Monitoring the state is recommended and described here.

Disposing the producer

The Producer implements IAsyncDisposable and should be disposed when it's no longer needed. Disposing the client will dispose all producers.