Skip to content
This repository has been archived by the owner on Feb 12, 2022. It is now read-only.

Latest commit

 

History

History
137 lines (118 loc) · 13.4 KB

README.md

File metadata and controls

137 lines (118 loc) · 13.4 KB

.NET Kafka Client

This is a .NET implementation of a client for Kafka using C# for Kafka 0.8. It provides for an implementation that covers most basic functionalities to include a simple Producer and Consumer.

Producer

The Producer can send one or more messages to Kafka in both a synchronous and asynchronous fashion.

Producer Usage

var producerConfig1 = new ProducerConfig();
producerConfig1.ProducerType = ProducerTypes.Async; // (or sync)
// ...
// other configuration settings (described below)
// ...
producerConfig1.Brokers = new List<BrokerConfiguration>
           {
              new BrokerConfiguration
                  {
                     BrokerId = 0, Host = "localhost", Port = 9092
                  }
          };
producerConfig1.KeySerializer = typeof(StringEncoder).AssemblyQualifiedName;
producerConfig1.Serializer = typeof(StringEncoder).AssemblyQualifiedName;
using (var producer1 = new Producer<string, string>(producerConfig1))
    producer1.Send(new KeyedMessage<string, string>(topic, "test", "test1"));
}

Producer Configuration Options

XML parameter name / Config class parameter name Default value Description
Brokers /Brokers - This is for bootstrapping and the producer will only use it for getting metadata (topics, partitions and replicas). The socket connections for sending the actual data will be established based on the broker information returned in the metadata.
partitioner /PartitionerClass DefaultPartitioner The partitioner class for partitioning messages amongst sub-topics. The default partitioner is based on the hash of the key.
type /ProducerType Sync This parameter specifies whether the messages are sent asynchronously in a background thread. Valid values are async for asynchronous send and sync for synchronous send. By setting the producer to async we allow batching together of requests (which is great for throughput) but open the possibility of a failure of the client machine dropping unsent data.
compressionCodec /CompressionCodec None This parameter allows you to specify the compression codec for all data generated by this producer.
compressedTopics / CompressedTopics Empty string list This parameter allows you to set whether compression should be turned on for particular topics. If the compression codec is anything other than NoCompressionCodec, enable compression only for specified topics if any. If the list of compressed topics is empty, then enable the specified compression codec for all topics. If the compression codec is NoCompressionCodec, compression is disabled for all topics
messageSendMaxRetries / MessageSendMaxRetries 3 This property will cause the producer to automatically retry a failed send request. This property specifies the number of retries when such failures occur. Note that setting a non-zero value here can lead to duplicates in the case of network errors that cause a message to be sent but the acknowledgement to be lost.
retryBackoffMs / RetryBackoffMs 100 Before each retry, the producer refreshes the metadata of relevant topics to see if a new leader has been elected. Since leader election takes a bit of time, this property specifies the amount of time that the producer waits before refreshing the metadata.
topicMetadataRefreshIntervalMs / TopicMetadataRefreshIntervalMs 600 * 1000 The producer generally refreshes the topic metadata from brokers when there is a failure (partition missing, leader not available...). It will also poll regularly (default: every 10min so 600000ms). If you set this to a negative value, metadata will only get refreshed on failure. If you set this to zero, the metadata will get refreshed after each message sent (not recommended). Important note: the refresh happen only AFTER the message is sent, so if the producer never sends a message the metadata is never refreshed
queueBufferingMaxMs / QueueBufferingMaxMs 5000 Maximum time to buffer data when using async mode. For example a setting of 100 will try to batch together 100ms of messages to send at once. This will improve throughput but adds message delivery latency due to the buffering.
queueBufferingMaxMessages / QueueBufferingMaxMessages 10000 The maximum number of unsent messages that can be queued up the producer when using async mode before either the producer must be blocked or data must be dropped.
queueEnqueueTimeoutMs / QueueEnqueueTimeoutMs -1 The amount of time to block before dropping messages when running in async mode and the buffer has reached queue.buffering.max.messages. If set to 0 events will be enqueued immediately or dropped if the queue is full (the producer send call will never block). If set to -1 the producer will block indefinitely and never willingly drop a send.
batchNumMessages / BatchNumMessages 200 The number of messages to send in one batch when using async mode. The producer will wait until either this number of messages are ready to send or queue.buffer.max.ms is reached.
sendBufferBytes /SendBufferBytes 100 * 1024 Socket write buffer size
clientId / ClientId "" The client id is a user-specified string sent in each request to help trace calls. It should logically identify the application making the request.
requestRequiredAcks / RequestRequiredAcks 0 This value controls when a produce request is considered completed. Specifically, how many other brokers must have committed the data to their log and acknowledged this to the leader? Typical values are
  • 0, which means that the producer never waits for an acknowledgement from the broker (the same behavior as 0.7). This option provides the lowest latency but the weakest durability guarantees (some data will be lost when a server fails).
  • 1, which means that the producer gets an acknowledgement after the leader replica has received the data. This option provides better durability as the client waits until the server acknowledges the request as successful (only messages that were written to the now-dead leader but not yet replicated will be lost).
  • -1, which means that the producer gets an acknowledgement after all in-sync replicas have received the data. This option provides the best durability, we guarantee that no messages will be lost as long as at least one in sync replica remains.
requestTimeoutMs / RequestTimeoutMs 10000 The amount of time the broker will wait trying to meet the request.required.acks requirement before sending back an error to the client.
serializer / Serializer kafka.serializer. DefaultEncoder he serializer class for messages. The default encoder takes a byte[] and returns the same byte[].
keySerializer / KeySerializer - The serializer class for keys (defaults to the same as for messages if nothing is given).

Sample producer configuration in App.config:

<configuration>
  <configSections>
    <section name="producer"
      type="Kafka.Client.Cfg.Sections.ProducerConfigurationSection, Kafka.Client" />
  </configSections>
  <producer type="Sync" serializer="Kafka.Client.Serializers.StringEncoder" keySerializer="Kafka.Client.Serializers.StringEncoder">
    <brokers>
      <add id="0" host="localhost" port="9092" />
    </brokers>
  </producer>
</configuration>

And invocation in application:

ProducerConfig configuration = ProducerConfig.configure("producer");

Consumer

The consumer has several functions of interest: CommitOffsets and CreateMessageStreams. CommitOffsets will commit offset that was already consumed by client. You can also configure to autocommit offsets. CreateMessageStreams creates streams from which we can read messages.

Consumer Usage

var consumerConfig1 = new ConsumerConfig("localhost", "2181", "group1");
var zkConsumerConnector1 = new ZookeeperConsumerConnector(consumerConfig1);
var topicMessageStreams1 =
    zkConsumerConnector1.CreateMessageStreams(
        new Dictionary<string, int> { { Topic, 1 } }, new StringDecoder(), new StringDecoder());

foreach (var messageAndMetadata in topicMessageStreams1[Topic][0])
{
    Console.WriteLine(messageAndMetadata.Message);
}

Consumer Configuration Options

XML parameter name / Config class parameter name Default value Description
groupId / GroupId REQUIRED A string that uniquely identifies the group of consumer processes to which this consumer belongs. By setting the same group id multiple processes indicate that they are all part of the same consumer group.
zookeeper / ZooKeeper REQUIRED Specifies the zookeeper locations
consumerId / ConsumerId null Generated automatically if not set.
socketTimeout / SocketTimeoutMs 30 * 1000 The socket timeout for network requests. The actual timeout set will be FetchWaitMaxMs + SocketTimeoutMs.
socketBufferSize / SocketReceiveBufferBytes 64 * 1024 The socket receive buffer for network requests
fetchSize / FetchMessageMaxBytes 1024 * 1024 The number of byes of messages to attempt to fetch for each topic-partition in each fetch request. These bytes will be read into memory for each partition, so this helps control the memory used by the consumer. The fetch request size must be at least as large as the maximum message size the server allows or else it is possible for the producer to send messages larger than the consumer can fetch.
numConsumerFetchers / NumConsumerFetchers 1 The number threads used to fetch data.
autoCommit / AutoCommitEnable true If true, periodically commit to zookeeper the offset of messages already fetched by the consumer. This committed offset will be used when the process fails as the position from which the new consumer will begin.
autoCommitInterval / AutoCommitIntervalMs 60 * 1000 The frequency in ms that the consumer offsets are committed to zookeeper.
maxQueuedChunks / QueuedMaxMessages 10 Max number of message chunks buffered for consumption. Each chunk can be up to FetchMessageMaxBytes
maxRebalanceRetries / RebalanceMaxRetries 4 When a new consumer joins a consumer group the set of consumers attempt to "rebalance" the load to assign partitions to each consumer. If the set of consumers changes while this assignment is taking place the rebalance will fail and retry. This setting controls the maximum number of attempts before giving up.
minFetchBytes / FetchMinBytes 1 The minimum amount of data the server should return for a fetch request. If insufficient data is available the request will wait for that much data to accumulate before answering the request.
maxFetchWaitMs / FetchWaitMaxMs 100 The maximum amount of time the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy FetchMinBytes
rebalanceBackoffMs / RebalanceBackoffMs 2000 Backoff time between retries during rebalance.
refreshMetadataBackoffMs / RefreshLeaderBackoffMs 200 Backoff time to wait before trying to determine the leader of a partition that has just lost its leader.
autoOffsetReset / AutoOffsetReset largest What to do when there is no initial offset in Zookeeper or if an offset is out of range:
  • smallest : automatically reset the offset to the smallest offset
  • largest : automatically reset the offset to the largest offset
  • anything else: throw exception to the consumer. If this is set to largest, the consumer may lose some messages when the number of partitions, for the topics it subscribes to, changes on the broker. To prevent data loss during partition addition, set AutoOffsetReset to smallest
consumerTimeoutMs / ConsumerTimeoutMs -1 Throw a timeout exception to the consumer if no message is available for consumption after the specified interval
clientId / ClientId group id value The client id is a user-specified string sent in each request to help trace calls. It should logically identify the application making the request.

Sample consumer configuration in App.config:

<configuration>
  <configSections>
    <section name="consumer"
      type="Kafka.Client.Cfg.Sections.ConsumerConfigurationSection, Kafka.Client" />
  </configSections>
  <consumer groupId="group1" >
    <zookeeper>
      <servers>
        <add host="localhost" port="2181" />
      </servers>
    </zookeeper>
  </consumer>
</configuration>

And invocation in application:

ConsumerConfig configuration = ConsumerConfig.Configure("consumer");