Apache Kafka 版本 1.1.0
Java版本的Consumer client
先看接口声明:
/*
* 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();
/**
* @see KafkaConsumer#subscription()
*/
public Set<String> subscription();
/**
* @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();
/**
* @see KafkaConsumer#poll(long)
*/
public ConsumerRecords<K, V> poll(long timeout);
/**
* @see KafkaConsumer#commitSync()
*/
public void commitSync();
/**
* @see KafkaConsumer#commitSync(Map)
*/
public void commitSync(Map<TopicPartition, OffsetAndMetadata> offsets);
/**
* @see KafkaConsumer#commitAsync()
*/
public void commitAsync();
/**
* @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();
/**
* @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();
/**
* @see KafkaConsumer#close(long, TimeUnit)
*/
public void close(long timeout, TimeUnit unit);
/**
* @see KafkaConsumer#wakeup()
*/
public void wakeup();
}
复制代码
Consumer的API可以分为以下几类:
- 订阅指定topic列表或者匹配某种模式的topic以及返回所订阅的topic列表和取消订阅
// 订阅指定的topic列表或者匹配某种模式的topic
/**
* 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);
复制代码
// 返回所订阅的topic列表
/**
* @see KafkaConsumer#subscription()
*/
public Set<String> subscription();
复制代码
// 取消订阅
/**
* @see KafkaConsumer#unsubscribe()
*/
public void unsubscribe();
复制代码
- 分配消费指定topic、获取分配的Topic分区
// 分配消费指定topic
/**
* @see KafkaConsumer#assign(Collection)
*/
public void assign(Collection<TopicPartition> partitions);
复制代码
// 获取分配的Topic分区
/**
* @see KafkaConsumer#assignment()
*/
public Set<TopicPartition> assignment();
复制代码
- 拉取数据
/**
* @see KafkaConsumer#poll(long)
*/
public ConsumerRecords<K, V> poll(long timeout);
复制代码
- 提交offsets
/**
* @see KafkaConsumer#commitSync()
*/
public void commitSync();
/**
* @see KafkaConsumer#commitSync(Map)
*/
public void commitSync(Map<TopicPartition, OffsetAndMetadata> offsets);
/**
* @see KafkaConsumer#commitAsync()
*/
public void commitAsync();
/**
* @see KafkaConsumer#commitAsync(OffsetCommitCallback)
*/
public void commitAsync(OffsetCommitCallback callback);
/**
* @see KafkaConsumer#commitAsync(Map, OffsetCommitCallback)
*/
public void commitAsync(Map<TopicPartition, OffsetAndMetadata> offsets, OffsetCommitCallback callback);
复制代码
- 定位、获取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);
复制代码
- 获取topic及topic分区信息
/**
* @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();
/**
* @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();
/**
* @see KafkaConsumer#close(long, TimeUnit)
*/
public void close(long timeout, TimeUnit unit);
/**
* @see KafkaConsumer#wakeup()
*/
public void wakeup();
复制代码
- 获取消费指标
/**
* @see KafkaConsumer#metrics()
*/
public Map<MetricName, ? extends Metric> metrics();
复制代码
一、初始化KafkaConsumer
KafkaConsumer有以下几个构造器:
其中常用的是 KafkaConsumer(Properties)
,传入的Properties对象,会转换为内部的ConsumerConfig对象,最终调用的是KafkaConsumer(ConsumerConfig config, Deserializer<K> keyDeserializer, Deserializer<V> valueDeserializer)
这个构造器,因此重点分析一下Properties转换为ConsumerConfig对象,看下有哪些配置参数,然后研究这个构造器里面的逻辑。
首先看下ConsumerConfig这个类,其中可以看到构造KafkaConsumer需要的参数:
参数 | 描述 | 默认值 |
---|---|---|
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 of all servers irrespective of which 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 form host1: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 * 60 * 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 via message.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):
|
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.MetricsReporter interface 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 * 60 * 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 Messages will always be returned in offset order. Hence, in Further, when in |
|
security.protocol | Protocol used to communicate with brokers. Valid values are: PLAINTEXT SSL SASL_PLAINTEXT SASL_SSL | PLAINTEXT |
KafkaConsumer构建步骤如下:
1)设置clientId
先从ConsumerConfig中取key为client.id
对应的值,如果没有设置,则生成一个,以 “consumer-” + CONSUMER_CLIENT_ID_SEQUENCE递增序列号;
2)设置groupId
从ConsumerConfig中取key为group.id
对应的值
3)设置requestTimeoutMs参数
从ConsumerConfig中取key为request.timeout.ms
对应的值
4)设置sessionTimeOutMs参数
从ConsumerConfig中取key为session.timeout.ms
对应的值
5)设置fetchMaxWaitMs参数
从ConsumerConfig中取key为fetch.max.wait.ms
对应的值
6)判断requestTimeoutMs是否大于sessionTimeOutMs和fetchMaxWaitMs
7)设置time
8)构建Metrics体系
9)设置retryBackoffMs
从ConsumerConfig中取key为retry.backoff.ms
对应的值
10)构建ConsumerInterceptor列表
11)设置keyDeserializer
12)设置valueDeserializer
13)配置构建ClusterResourceListeners
14)构建MetaData实例
这步只是新建了一个Metadata对象,并设置了相关参数,但是还没有访问Kafka集群真正去获取元数据
15)根据bootstrap.servers参数生成InetSocketAddress
16)更新元数据Metadata
构造Cluster对象,包括节点、topic、topic分区及其它们之间关系索引,这里也没有真正获取元数据,只根据bootstrap.servers参数补充了Node信息
17)构建 ChannelBuilder
18)获取IsolationLevel
从ConsumerConfig中取key为isolation.level
对应的值
19)获取heartbeatIntervalMs参数
20)构建NetworkClient
这是构建KafkaConsumer很关键的一步,在这一步里面,先新建了一个Selector对象(NIO Selector)。
21)构建ConsumerNetworkClient对象
22)获取OffsetResetStrategy
23)构建PartitionAssignor
即创建RangeAssignor实例
24)构建ConsumerCoordinator
25)构建Fetcher
其中关键对象是Fetcher、ConsumerCoordinator、ConsumerNetworkClient、NetworkClient。