Apache Kafka version 1.1.0

The Java version of Consumer Client

First look at the interface declaration:

/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE  file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this File to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the  License. */
package org.apache.kafka.clients.consumer;

import org.apache.kafka.common.Metric;
import org.apache.kafka.common.MetricName;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;

import java.io.Closeable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/ * * *@see KafkaConsumer
 * @see MockConsumer
 */
public interface Consumer<K.V> extends Closeable {

    / * * *@see KafkaConsumer#assignment()
     */
    public Set<TopicPartition> assignment(a);

    / * * *@see KafkaConsumer#subscription()
     */
    public Set<String> subscription(a);

    / * * *@see KafkaConsumer#subscribe(Collection)
     */
    public void subscribe(Collection<String> topics);

    / * * *@see KafkaConsumer#subscribe(Collection, ConsumerRebalanceListener)
     */
    public void subscribe(Collection<String> topics, ConsumerRebalanceListener callback);

    / * * *@see KafkaConsumer#assign(Collection)
     */
    public void assign(Collection<TopicPartition> partitions);

    / * * *@see KafkaConsumer#subscribe(Pattern, ConsumerRebalanceListener)
    */
    public void subscribe(Pattern pattern, ConsumerRebalanceListener callback);

    / * * *@see KafkaConsumer#subscribe(Pattern)
    */
    public void subscribe(Pattern pattern);

    / * * *@see KafkaConsumer#unsubscribe()
     */
    public void unsubscribe(a);

    / * * *@see KafkaConsumer#poll(long)
     */
    public ConsumerRecords<K, V> poll(long timeout);

    / * * *@see KafkaConsumer#commitSync()
     */
    public void commitSync(a);

    / * * *@see KafkaConsumer#commitSync(Map)
     */
    public void commitSync(Map<TopicPartition, OffsetAndMetadata> offsets);

    / * * *@see KafkaConsumer#commitAsync()
     */
    public void commitAsync(a);

    / * * *@see KafkaConsumer#commitAsync(OffsetCommitCallback)
     */
    public void commitAsync(OffsetCommitCallback callback);

    / * * *@see KafkaConsumer#commitAsync(Map, OffsetCommitCallback)
     */
    public void commitAsync(Map<TopicPartition, OffsetAndMetadata> offsets, OffsetCommitCallback callback);

    / * * *@see KafkaConsumer#seek(TopicPartition, long)
     */
    public void seek(TopicPartition partition, long offset);

    / * * *@see KafkaConsumer#seekToBeginning(Collection)
     */
    public void seekToBeginning(Collection<TopicPartition> partitions);

    / * * *@see KafkaConsumer#seekToEnd(Collection)
     */
    public void seekToEnd(Collection<TopicPartition> partitions);

    / * * *@see KafkaConsumer#position(TopicPartition)
     */
    public long position(TopicPartition partition);

    / * * *@see KafkaConsumer#committed(TopicPartition)
     */
    public OffsetAndMetadata committed(TopicPartition partition);

    / * * *@see KafkaConsumer#metrics()
     */
    public Map<MetricName, ? extends Metric> metrics();

    / * * *@see KafkaConsumer#partitionsFor(String)
     */
    public List<PartitionInfo> partitionsFor(String topic);

    / * * *@see KafkaConsumer#listTopics()
     */
    public Map<String, List<PartitionInfo>> listTopics();

    / * * *@see KafkaConsumer#paused()
     */
    public Set<TopicPartition> paused(a);

    / * * *@see KafkaConsumer#pause(Collection)
     */
    public void pause(Collection<TopicPartition> partitions);

    / * * *@see KafkaConsumer#resume(Collection)
     */
    public void resume(Collection<TopicPartition> partitions);

    / * * *@see KafkaConsumer#offsetsForTimes(java.util.Map)
     */
    public Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(Map<TopicPartition, Long> timestampsToSearch);

    / * * *@see KafkaConsumer#beginningOffsets(java.util.Collection)
     */
    public Map<TopicPartition, Long> beginningOffsets(Collection<TopicPartition> partitions);

    / * * *@see KafkaConsumer#endOffsets(java.util.Collection)
     */
    public Map<TopicPartition, Long> endOffsets(Collection<TopicPartition> partitions);

    / * * *@see KafkaConsumer#close()
     */
    public void close(a);

    / * * *@see KafkaConsumer#close(long, TimeUnit)
     */
    public void close(long timeout, TimeUnit unit);

    / * * *@see KafkaConsumer#wakeup()
     */
    public void wakeup(a);

}

Copy the code

Consumer apis fall into the following categories:

  1. Subscribe to a list of specified topics or topics that match a pattern and return the list of subscribed topics and unsubscribe

Subscribe to a list of topics or topics that match a pattern

    
        /**
         * Subscribe to the given list of topics to get dynamically assigned partitions.
         * <b>Topic subscriptions are not incremental. This list will replace the current
         * assignment (if there is one).</b> It is not possible to combine topic subscription with group management
         * with manual partition assignment through {@link #assign(Collection)}.
         *
         * If the given list of topics is empty, it is treated the same as {@link #unsubscribe()}.
         *
         * <p>
         * This is a short-hand for {@link #subscribe(Collection, ConsumerRebalanceListener)}, which
         * uses a no-op listener. If you need the ability to seek to particular offsets, you should prefer
         * {@link #subscribe(Collection, ConsumerRebalanceListener)}, since group rebalances will cause partition offsets
         * to be reset. You should also provide your own listener if you are doing your own offset
         * management since the listener gives you an opportunity to commit offsets before a rebalance finishes.
         *
         * @param topics The list of topics to subscribe to
         * @throws IllegalArgumentException If topics is null or contains null or empty elements
         * @throws IllegalStateException If {@code subscribe()} is called previously with pattern, or assign is called
         *                               previously (without a subsequent call to {@link #unsubscribe()}), or if not
         *                               configured at-least one partition assignment strategy
     */
    public void subscribe(Collection<String> topics);

    / * * *@see KafkaConsumer#subscribe(Collection, ConsumerRebalanceListener)
     */
    public void subscribe(Collection<String> topics, ConsumerRebalanceListener callback);
        / * * *@see KafkaConsumer#subscribe(Pattern, ConsumerRebalanceListener)
    */
    public void subscribe(Pattern pattern, ConsumerRebalanceListener callback);

    / * * *@see KafkaConsumer#subscribe(Pattern)
    */
    public void subscribe(Pattern pattern);
Copy the code

// Returns a list of subscribed topics

    / * * *@see KafkaConsumer#subscription()
     */
    public Set<String> subscription(a);
Copy the code

// Unsubscribe

    / * * *@see KafkaConsumer#unsubscribe()
     */
    public void unsubscribe(a);
Copy the code
  1. Distribution consumes the assigned topic and gets the assigned Topic partition

// Allocate consumption to the specified topic


    / * * *@see KafkaConsumer#assign(Collection)
     */
    public void assign(Collection<TopicPartition> partitions);
Copy the code

// Get the assigned Topic partition

    / * * *@see KafkaConsumer#assignment()
     */
    public Set<TopicPartition> assignment(a);
Copy the code
  1. Pull the data
    / * * *@see KafkaConsumer#poll(long)
     */
    public ConsumerRecords<K, V> poll(long timeout);
Copy the code
  1. Submit offsets
    / * * *@see KafkaConsumer#commitSync()
     */
    public void commitSync(a);

    / * * *@see KafkaConsumer#commitSync(Map)
     */
    public void commitSync(Map<TopicPartition, OffsetAndMetadata> offsets);

    / * * *@see KafkaConsumer#commitAsync()
     */
    public void commitAsync(a);

    / * * *@see KafkaConsumer#commitAsync(OffsetCommitCallback)
     */
    public void commitAsync(OffsetCommitCallback callback);

    / * * *@see KafkaConsumer#commitAsync(Map, OffsetCommitCallback)
     */
    public void commitAsync(Map<TopicPartition, OffsetAndMetadata> offsets, OffsetCommitCallback callback);
Copy the code
  1. Locate and obtain offsets
    / * * *@see KafkaConsumer#seek(TopicPartition, long)
     */
    public void seek(TopicPartition partition, long offset);

    / * * *@see KafkaConsumer#seekToBeginning(Collection)
     */
    public void seekToBeginning(Collection<TopicPartition> partitions);

    / * * *@see KafkaConsumer#seekToEnd(Collection)
     */
    public void seekToEnd(Collection<TopicPartition> partitions);

    / * * *@see KafkaConsumer#position(TopicPartition)
     */
    public long position(TopicPartition partition);
        / * * *@see KafkaConsumer#committed(TopicPartition)
     */
    public OffsetAndMetadata committed(TopicPartition partition);
        / * * *@see KafkaConsumer#offsetsForTimes(java.util.Map)
     */
    public Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(Map<TopicPartition, Long> timestampsToSearch);
        / * * *@see KafkaConsumer#beginningOffsets(java.util.Collection)
     */
    public Map<TopicPartition, Long> beginningOffsets(Collection<TopicPartition> partitions);

    / * * *@see KafkaConsumer#endOffsets(java.util.Collection)
     */
    public Map<TopicPartition, Long> endOffsets(Collection<TopicPartition> partitions);
Copy the code
  1. Get topic and topic partition information
    / * * *@see KafkaConsumer#partitionsFor(String)
     */
    public List<PartitionInfo> partitionsFor(String topic);

    / * * *@see KafkaConsumer#listTopics()
     */
    public Map<String, List<PartitionInfo>> listTopics();
Copy the code
  1. Control consumption behavior (pause, resume, wake up, close)
    / * * *@see KafkaConsumer#paused()
     */
    public Set<TopicPartition> paused(a);

    / * * *@see KafkaConsumer#pause(Collection)
     */
    public void pause(Collection<TopicPartition> partitions);

    / * * *@see KafkaConsumer#resume(Collection)
     */
    public void resume(Collection<TopicPartition> partitions);
        / * * *@see KafkaConsumer#close()
     */
    public void close(a);

    / * * *@see KafkaConsumer#close(long, TimeUnit)
     */
    public void close(long timeout, TimeUnit unit);

    / * * *@see KafkaConsumer#wakeup()
     */
    public void wakeup(a);
Copy the code
  1. Get consumption indicators
    / * * *@see KafkaConsumer#metrics()
     */
    public Map<MetricName, ? extends Metric> metrics();
Copy the code

Initialize KafkaConsumer

KafkaConsumer has the following constructors:

The most common one is KafkaConsumer(Properties), where the passed Properties object is converted to the internal ConsumerConfig object, KafkaConsumer(ConsumerConfig config, Deserializer

keyDeserializer, Deserializer

valueDeserializer) So focus on the conversion of Properties to the ConsumerConfig object, see what configuration parameters are available, and then explore the logic inside the constructor.

First look at the ConsumerConfig class, where you can see the arguments required to construct KafkaConsumer:

parameter describe The default value
group.id A unique string that identifies the consumer group this consumer belongs to. This property is required if the consumer uses either the group management functionality by using subscribe(topic) or the Kafka-based offset management strategy.
bootstrap.servers A list of host/port pairs to use for establishing the initial connection to the Kafka cluster. The client will make use For all servers, THROUGHoutwhich servers are specified here for bootstrapping — this list only impacts the initial hosts used to discover the full set of servers. This list should be in the formhost1:port1,host2:port2,.... Since these servers are just used for the initial connection to discover the full cluster membership (which may change dynamically), this list need not contain the full set of servers (you may want more than one, though, in case a server is down).
session.timeout.ms The timeout used to detect consumer failures when using Kafka’s group management facility. The consumer sends periodic heartbeats to indicate its liveness to the broker. If no heartbeats are received by the broker before the expiration of this session timeout, then the broker will remove this consumer from the group and initiate a rebalance. Note that the value must be in the allowable range as configured in the broker configuration by group.min.session.timeout.ms and group.max.session.timeout.ms. 10000
heartbeat.interval.ms The expected time between heartbeats to the consumer coordinator when using Kafka’s group management facilities. Heartbeats are used to ensure that the consumer’s session stays active and to facilitate rebalancing when new consumers join or leave the group. The value must be set lower than session.timeout.ms. but typically should be set no higher than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances. 3000
partition.assignment.strategy The class name of the partition assignment strategy that the client will use to distribute partition ownership amongst consumer instances when group management is used org.apache.kafka.clients.consumer.RangeAssignor
metadata.max.age.ms The period of time in milliseconds after which we force a refresh of metadata even if we haven’t seen any partition leadership changes to proactively discover any new brokers or partitions. 5 times 60 times 1000
enable.auto.commit If true the consumer’s offset will be periodically committed in the background. true
auto.commit.interval.ms The frequency in milliseconds that the consumer offsets are auto-committed to Kafka if enable.auto.commit is set to true. 5000
client.id An id string to pass to the server when making requests. The purpose of this is to be able to track the source of requests beyond just ip/port by allowing a logical application name to be included in server-side request logging.
max.partition.fetch.bytes max.partition.fetch.bytes will return. Records are fetched in batches by the consumer. If the first record batch in the first non-empty partition of the fetch is larger than this limit, the batch will still be returned to ensure that the consumer can make progress. The maximum record batch size accepted by the broker is defined via message.max.bytes (broker config) or max.message.bytes (topic config). See ‘fetch.max.bytes’ for limiting the consumer request size. 1MB
send.buffer.bytes The size of the TCP send buffer (SO_SNDBUF) to use when sending data. If the value is -1, the OS default will be used. 128 * 1024
receive.buffer.bytes The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. If the value is -1, the OS default will be used. 64 * 1024
fetch.min.bytes 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. The default setting of 1 byte means that fetch requests are answered as soon as a single byte of data is available or the fetch request times out waiting for data to arrive. Setting this to something greater than 1 will cause the server to wait for larger amounts of data to accumulate which can improve server throughput a bit at the cost of some additional latency. 1
fetch.max.bytes The maximum amount of data the server should return for a fetch request. Records are fetched in batches by the consumer, and if the first record batch in the first non-empty partition of the fetch is larger than this value, the record batch will still be returned to ensure that the consumer can make progress. As such, this is not a absolute maximum. The maximum record batch size accepted by the broker is defined viamessage.max.bytes (broker config) or max.message.bytes (topic config). Note that the consumer performs multiple fetches in parallel. 50 * 1024 * 1024
fetch.max.wait.ms The maximum amount of time the server will block before answering the fetch request if there isn’t sufficient data to immediately satisfy the requirement given by fetch.min.bytes. 500
reconnect.backoff.ms The base amount of time to wait before attempting to reconnect to a given host. This avoids repeatedly connecting to a host in a tight loop. This backoff applies to all connection attempts by the client to a broker. 50
reconnect.backoff.max.ms The maximum amount of time in milliseconds to wait when reconnecting to a broker that has repeatedly failed to connect. If provided, the backoff per host will increase exponentially for each consecutive connection failure, up to this maximum. After calculating the backoff increase, 20% random jitter is added to avoid connection storms. 1000L
retry.backoff.ms The amount of time to wait before attempting to retry a failed request to a given topic partition. This avoids repeatedly sending requests in a tight loop under some failure scenarios. 100L
auto.offset.reset What to do when there is no initial offset in Kafka or if the current offset does not exist any more on the server (e.g. because that data has been deleted):

  • earliest: automatically reset the offset to the earliest offset
  • latest: automatically reset the offset to the latest offset
  • none: throw exception to the consumer if no previous offset is found for the consumer’s group
  • anything else: throw exception to the consumer.
latest
check.crcs Automatically check the CRC32 of the records consumed. This ensures no on-the-wire or on-disk corruption to the messages occurred. This check adds some overhead, so it may be disabled in cases seeking extreme performance. true
metrics.sample.window.ms The window of time a metrics sample is computed over. 30000
metrics.num.samples The number of samples maintained to compute metrics. 30000
metrics.recording.level The highest recording level for metrics. INFO
metric.reporters A list of classes to use as metrics reporters. Implementing the org.apache.kafka.common.metrics.MetricsReporterinterface allows plugging in classes that will be notified of new metric creation. The JmxReporter is always included to register JMX statistics.
key.deserializer Deserializer class for key that implements the org.apache.kafka.common.serialization.Deserializer interface.
value.deserializer Deserializer class for value that implements the org.apache.kafka.common.serialization.Deserializer interface.
request.timeout.ms The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses the client will resend the request if necessary or fail the request if retries are exhausted. 305000
connections.max.idle.ms Close idle connections after the number of milliseconds specified by this config. 9 times 60 times 1000
interceptor.classes A list of classes to use as interceptors. Implementing the org.apache.kafka.clients.consumer.ConsumerInterceptor interface allows you to intercept (and possibly mutate) records received by the consumer. By default, there are no interceptors.
max.poll.records The maximum number of records returned in a single call to poll(). 500
max.poll.interval.ms The maximum delay between invocations of poll() when using consumer group management. This places an upper bound on the amount of time that the consumer can be idle before fetching more records. If poll() is not called before expiration of this timeout, then the consumer is considered failed and the group will rebalance in order to reassign the partitions to another member. 300000
exclude.internal.topics Whether records from internal topics (such as offsets) should be exposed to the consumer. If set to true the only way to receive records from an internal topic is subscribing to it. true
internal.leave.group.on.close Whether or not the consumer should leave the group on close. If set to false then a rebalance won’t occur until session.timeout.ms expires.
isolation.level

Controls how to read messages written transactionally. If set to read_committed, consumer.poll() will only return transactional messages which have been committed. If set to read_uncommitted‘ (the default), consumer.poll() will return all messages, even transactional messages which have been aborted. Non-transactional messages will be returned unconditionally in either mode.

Messages will always be returned in offset order. Hence, in read_committed mode, consumer.poll() will only return messages up to the last stable offset (LSO), which is the one less than the offset of the first open transaction. In particular any messages appearing after messages belonging to ongoing transactions will be withheld until the relevant transaction has been completed. As a result, read_committed consumers will not be able to read up to the high watermark when there are in flight transactions.

Further, when in read_committed the seekToEnd method will return the LSO

security.protocol Protocol used to communicate with brokers. Valid values are: PLAINTEXT SSL SASL_PLAINTEXT SASL_SSL PLAINTEXT

The KafkaConsumer build steps are as follows:

1) Set clientId

First fetch the key from ConsumerConfig as the corresponding value of client.id. If this is not set, generate one, incrementing the sequence number with “consumer-” + CONSUMER_CLIENT_ID_SEQUENCE.

2) Set groupId

Select key from ConsumerConfig for group.id

3) Set requestTimeoutMs parameters

Take the value of request.timeout.ms from ConsumerConfig

4) Set the sessionTimeOutMs parameter

Retrieve key from ConsumerConfig for session.timeout.ms

Set the fetchMaxWaitMs parameter

Fetch the key from ConsumerConfig as fetch. Max.wait. ms

6) Check whether requestTimeoutMs is greater than sessionTimeOutMs and fetchMaxWaitMs

7) Set time

8) Build Metrics

9) Set retryBackoffMs

Fetches the value of retry.backoff.ms from ConsumerConfig

10) Build the ConsumerInterceptor list

11) Set the keyDeserializer

12) Set valueDeserializer

13) Configure ClusterResourceListeners

14) Build MetaData instances

This step simply creates a Metadata object and sets the parameters, but does not access the Kafka cluster to actually fetch the Metadata

15) Generate the InetSocketAddress according to the bootstrap.servers parameter

16) Update Metadata

The Cluster object consists of nodes, topics, topic partitions, and index relationships between them. No metadata is actually retrieved here, but Node information is supplemented by the bootstrap.servers parameter

17) Build ChannelBuilder

18) Obtain IsolationLevel

Take key from ConsumerConfig to isolation.level

19) Get the heartbeatIntervalMs parameter

20) Build NetworkClient

This is a key step in building KafkaConsumer, where you create a new Selector object (NIO Selector).

21) Construct the ConsumerNetworkClient object

22) Get OffsetResetStrategy

23) Construct PartitionAssignor

Create RangeAssignor instance

24) Build the ConsumerCoordinator

25) Build Fetcher

The key objects are Fetcher, ConsumerCoordinator, ConsumerNetworkClient, and NetworkClient.

Subscribe Topic list