当前位置:   article > 正文

Kafka源码分析之Producer(一)_kafkaproducer 源码解析

kafkaproducer 源码解析

总览

根据kafka的3.1.0的源码example模块进行分析,如下图所示,一般实例代码就是我们分析源码的入口

可以将produce的发送主要流程概述如下:

  1. 拦截器对发送的消息拦截处理;

  2. 获取元数据信息;

  3. 序列化处理;

  4. 分区处理;

  5. 批次添加处理;

  6. 发送消息。

总的大概是上面六个步骤,下面将结合源码对每个步骤进行分析。

1. 拦截器 

消息拦截器在消息发送开始阶段进行拦截,this method does not throw exceptions注释加上代码可以看出即使拦截器抛出异常也不会中止我们的消息发送。

使用场景:发送消息的统一处理类似spring的拦截器动态切入功能,自定义拦截器打印日志、统计时间、持久化到本地数据库等。

  1. @Override
  2. public Future<RecordMetadata> send(ProducerRecord<K, V> record, Callback callback) {
  3. // intercept the record, which can be potentially modified; this method does not throw exceptions
  4. //1.拦截器对发送的消息拦截处理;
  5. ProducerRecord<K, V> interceptedRecord = this.interceptors.onSend(record);
  6. return doSend(interceptedRecord, callback);
  7. }
  8. public ProducerRecord<K, V> onSend(ProducerRecord<K, V> record) {
  9. ProducerRecord<K, V> interceptRecord = record;
  10. for (ProducerInterceptor<K, V> interceptor : this.interceptors) {
  11. try {
  12. interceptRecord = interceptor.onSend(interceptRecord);
  13. } catch (Exception e) {
  14. // do not propagate interceptor exception, log and continue calling other interceptors
  15. // be careful not to throw exception from here
  16. if (record != null)
  17. log.warn("Error executing interceptor onSend callback for topic: {}, partition: {}", record.topic(), record.partition(), e);
  18. else
  19. log.warn("Error executing interceptor onSend callback", e);
  20. }
  21. }
  22. return interceptRecord;
  23. }

2. 获取元数据信息

下图是发送消息主线程和发送网络请求sender线程配合获取元数据的流程:

首先找到获取kafka的元数据信息的入口,maxBlockTimeMs最大的等待时间是60s:

  1. try {
  2. //2.获取元数据信息;
  3. clusterAndWaitTime = waitOnMetadata(record.topic(), record.partition(), nowMs, maxBlockTimeMs);
  4. } catch (KafkaException e) {
  5. if (metadata.isClosed())
  6. throw new KafkaException("Producer closed while send in progress", e);
  7. throw e;
  8. }
  9. .define(MAX_BLOCK_MS_CONFIG,
  10. Type.LONG,
  11. 60 * 1000,
  12. atLeast(0),
  13. Importance.MEDIUM,
  14. MAX_BLOCK_MS_DOC)

 这里唤醒sender线程,然后阻塞等待元数据信息;

  1. metadata.add(topic, nowMs + elapsed);
  2. int version = metadata.requestUpdateForTopic(topic);
  3. //唤醒线程更新元数据
  4. sender.wakeup();
  5. try {
  6. //阻塞等待
  7. metadata.awaitUpdate(version, remainingWaitMs);
  8. } catch (TimeoutException ex) {
  9. // Rethrow with original maxWaitMs to prevent logging exception with remainingWaitMs
  10. throw new TimeoutException(
  11. String.format("Topic %s not present in metadata after %d ms.",
  12. topic, maxWaitMs));
  13. }

这里可以看一下 sender线程的初始化参数:

.define(BUFFER_MEMORY_CONFIG, Type.LONG, 32 * 1024 * 1024L, atLeast(0L), Importance.HIGH, BUFFER_MEMORY_DOC) 初始化内存池的大小为32M;
.define(MAX_REQUEST_SIZE_CONFIG,
        Type.INT,
        1024 * 1024,
        atLeast(0),
        Importance.MEDIUM,
        MAX_REQUEST_SIZE_DOC) 默认单条消息最大为1M;

构造函数中初始化了sender,并作为守护线程在后台运行:

  1. this.sender = newSender(logContext, kafkaClient, this.metadata);
  2. String ioThreadName = NETWORK_THREAD_PREFIX + " | " + clientId;
  3. this.ioThread = new KafkaThread(ioThreadName, this.sender, true);
  4. this.ioThread.start();
  1. KafkaProducer(ProducerConfig config,
  2. Serializer<K> keySerializer,
  3. Serializer<V> valueSerializer,
  4. ProducerMetadata metadata,
  5. KafkaClient kafkaClient,
  6. ProducerInterceptors<K, V> interceptors,
  7. Time time) {
  8. try {
  9. ...
  10. this.maxRequestSize = config.getInt(ProducerConfig.MAX_REQUEST_SIZE_CONFIG);
  11. this.totalMemorySize = config.getLong(ProducerConfig.BUFFER_MEMORY_CONFIG);
  12. this.compressionType = CompressionType.forName(config.getString(ProducerConfig.COMPRESSION_TYPE_CONFIG));
  13. this.maxBlockTimeMs = config.getLong(ProducerConfig.MAX_BLOCK_MS_CONFIG);
  14. int deliveryTimeoutMs = configureDeliveryTimeout(config, log);
  15. this.apiVersions = new ApiVersions();
  16. this.transactionManager = configureTransactionState(config, logContext);
  17. this.accumulator = new RecordAccumulator(logContext,
  18. config.getInt(ProducerConfig.BATCH_SIZE_CONFIG),
  19. this.compressionType,
  20. lingerMs(config),
  21. retryBackoffMs,
  22. deliveryTimeoutMs,
  23. metrics,
  24. PRODUCER_METRIC_GROUP_NAME,
  25. time,
  26. apiVersions,
  27. transactionManager,
  28. new BufferPool(this.totalMemorySize, config.getInt(ProducerConfig.BATCH_SIZE_CONFIG), metrics, time, PRODUCER_METRIC_GROUP_NAME));
  29. ...
  30. this.errors = this.metrics.sensor("errors");
  31. this.sender = newSender(logContext, kafkaClient, this.metadata);
  32. String ioThreadName = NETWORK_THREAD_PREFIX + " | " + clientId;
  33. this.ioThread = new KafkaThread(ioThreadName, this.sender, true);
  34. this.ioThread.start();
  35. config.logUnused();
  36. AppInfoParser.registerAppInfo(JMX_PREFIX, clientId, metrics, time.milliseconds());
  37. log.debug("Kafka producer started");
  38. } catch (Throwable t) {
  39. // call close methods if internal objects are already constructed this is to prevent resource leak. see KAFKA-2121
  40. close(Duration.ofMillis(0), true);
  41. // now propagate the exception
  42. throw new KafkaException("Failed to construct kafka producer", t);
  43. }
  44. }
.define(ACKS_CONFIG,
        Type.STRING,
        "all",
        in("all", "-1", "0", "1"),
        Importance.LOW,
        ACKS_DOC) 默认所有broker同步消息才算发送成功;

.define(MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION,
        Type.INT,
        5,
        atLeast(1),
        Importance.LOW,
        MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION_DOC) 默认允许最多5个连接来发送消息;如果需要保证顺序消息需要将其设置为1.
  1. Sender newSender(LogContext logContext, KafkaClient kafkaClient, ProducerMetadata metadata) {
  2. int maxInflightRequests = configureInflightRequests(producerConfig);
  3. int requestTimeoutMs = producerConfig.getInt(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG);
  4. ChannelBuilder channelBuilder = ClientUtils.createChannelBuilder(producerConfig, time, logContext);
  5. ProducerMetrics metricsRegistry = new ProducerMetrics(this.metrics);
  6. Sensor throttleTimeSensor = Sender.throttleTimeSensor(metricsRegistry.senderMetrics);
  7. KafkaClient client = kafkaClient != null ? kafkaClient : new NetworkClient(
  8. new Selector(producerConfig.getLong(ProducerConfig.CONNECTIONS_MAX_IDLE_MS_CONFIG),
  9. this.metrics, time, "producer", channelBuilder, logContext),
  10. metadata,
  11. clientId,
  12. maxInflightRequests,
  13. producerConfig.getLong(ProducerConfig.RECONNECT_BACKOFF_MS_CONFIG),
  14. producerConfig.getLong(ProducerConfig.RECONNECT_BACKOFF_MAX_MS_CONFIG),
  15. producerConfig.getInt(ProducerConfig.SEND_BUFFER_CONFIG),
  16. producerConfig.getInt(ProducerConfig.RECEIVE_BUFFER_CONFIG),
  17. requestTimeoutMs,
  18. producerConfig.getLong(ProducerConfig.SOCKET_CONNECTION_SETUP_TIMEOUT_MS_CONFIG),
  19. producerConfig.getLong(ProducerConfig.SOCKET_CONNECTION_SETUP_TIMEOUT_MAX_MS_CONFIG),
  20. time,
  21. true,
  22. apiVersions,
  23. throttleTimeSensor,
  24. logContext);
  25. short acks = configureAcks(producerConfig, log);
  26. return new Sender(logContext,
  27. client,
  28. metadata,
  29. this.accumulator,
  30. maxInflightRequests == 1,
  31. producerConfig.getInt(ProducerConfig.MAX_REQUEST_SIZE_CONFIG),
  32. acks,
  33. producerConfig.getInt(ProducerConfig.RETRIES_CONFIG),
  34. metricsRegistry.senderMetrics,
  35. time,
  36. requestTimeoutMs,
  37. producerConfig.getLong(ProducerConfig.RETRY_BACKOFF_MS_CONFIG),
  38. this.transactionManager,
  39. apiVersions);
  40. }

 等待元数据的版本更新,挂起当前线程直到超时或者唤醒:

  1. public synchronized void awaitUpdate(final int lastVersion, final long timeoutMs) throws InterruptedException {
  2. long currentTimeMs = time.milliseconds();
  3. long deadlineMs = currentTimeMs + timeoutMs < 0 ? Long.MAX_VALUE : currentTimeMs + timeoutMs;
  4. time.waitObject(this, () -> {
  5. // Throw fatal exceptions, if there are any. Recoverable topic errors will be handled by the caller.
  6. maybeThrowFatalException();
  7. return updateVersion() > lastVersion || isClosed();
  8. }, deadlineMs);
  9. if (isClosed())
  10. throw new KafkaException("Requested metadata update after close");
  11. }
  12. public void waitObject(Object obj, Supplier<Boolean> condition, long deadlineMs) throws InterruptedException {
  13. synchronized (obj) {
  14. while (true) {
  15. if (condition.get())
  16. return;
  17. long currentTimeMs = milliseconds();
  18. if (currentTimeMs >= deadlineMs)
  19. throw new TimeoutException("Condition not satisfied before deadline");
  20. obj.wait(deadlineMs - currentTimeMs);
  21. }
  22. }
  23. }

 Sende通过NetWorkClient向kafak集群拉取元数据信息:

  1. Sender
  2. void runOnce() {
  3. client.poll(pollTimeout, currentTimeMs);
  4. }
  5. NetWorkClient:
  6. public List<ClientResponse> poll(long timeout, long now) {
  7. ensureActive();
  8. if (!abortedSends.isEmpty()) {
  9. // If there are aborted sends because of unsupported version exceptions or disconnects,
  10. // handle them immediately without waiting for Selector#poll.
  11. List<ClientResponse> responses = new ArrayList<>();
  12. handleAbortedSends(responses);
  13. completeResponses(responses);
  14. return responses;
  15. }
  16. long metadataTimeout = metadataUpdater.maybeUpdate(now);
  17. try {
  18. this.selector.poll(Utils.min(timeout, metadataTimeout, defaultRequestTimeoutMs));
  19. } catch (IOException e) {
  20. log.error("Unexpected error during I/O", e);
  21. }
  22. // process completed actions
  23. long updatedNow = this.time.milliseconds();
  24. List<ClientResponse> responses = new ArrayList<>();
  25. handleCompletedSends(responses, updatedNow);
  26. handleCompletedReceives(responses, updatedNow);
  27. handleDisconnections(responses, updatedNow);
  28. handleConnections();
  29. handleInitiateApiVersionRequests(updatedNow);
  30. handleTimedOutConnections(responses, updatedNow);
  31. handleTimedOutRequests(responses, updatedNow);
  32. completeResponses(responses);
  33. return responses;
  34. }

如下代码 handleCompletedReceives处理返回元数据的响应,然后调用handleSuccessfulResponse处理成功的响应,最后调用ProducerMetadata更新本地元数据信息并唤醒了主线程。主线程获取到元数据后进行下面流程。

  1. //NetWorkClient
  2. private void handleCompletedReceives(List<ClientResponse> responses, long now) {
  3. ...
  4. if (req.isInternalRequest && response instanceof MetadataResponse)
  5. metadataUpdater.handleSuccessfulResponse(req.header, now, (MetadataResponse) response);
  6. }
  7. public void handleSuccessfulResponse(RequestHeader requestHeader, long now, MetadataResponse response) {
  8. ...
  9. this.metadata.update(inProgress.requestVersion, response, inProgress.isPartialUpdate, now);
  10. }
  11. //ProducerMetadata
  12. public synchronized void update(int requestVersion, MetadataResponse response, boolean isPartialUpdate, long nowMs) {
  13. super.update(requestVersion, response, isPartialUpdate, nowMs);
  14. // Remove all topics in the response that are in the new topic set. Note that if an error was encountered for a
  15. // new topic's metadata, then any work to resolve the error will include the topic in a full metadata update.
  16. if (!newTopics.isEmpty()) {
  17. for (MetadataResponse.TopicMetadata metadata : response.topicMetadata()) {
  18. newTopics.remove(metadata.topic());
  19. }
  20. }
  21. notifyAll();
  22. }

3. 序列化处理

根据初始化的序列化器将消息的key和value进行序列化,以便后续发送网络请求:

  1. byte[] serializedKey;
  2. try {
  3. serializedKey = keySerializer.serialize(record.topic(), record.headers(), record.key());
  4. System.out.println("serializedKey:" + Arrays.toString(serializedKey));
  5. } catch (ClassCastException cce) {
  6. throw new SerializationException("Can't convert key of class " + record.key().getClass().getName() +
  7. " to class " + producerConfig.getClass(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG).getName() +
  8. " specified in key.serializer", cce);
  9. }
  10. byte[] serializedValue;
  11. try {
  12. serializedValue = valueSerializer.serialize(record.topic(), record.headers(), record.value());
  13. } catch (ClassCastException cce) {
  14. throw new SerializationException("Can't convert value of class " + record.value().getClass().getName() +
  15. " to class " + producerConfig.getClass(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG).getName() +
  16. " specified in value.serializer", cce);
  17. }

4.分区处理

消息有设置key根据hash值分区,没有key采用粘性分区的方式,详情可以看下面博客Kafka生产者的粘性分区算法_张家老院子的博客-CSDN博客

  1. public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster,
  2. int numPartitions) {
  3. if (keyBytes == null) {
  4. return stickyPartitionCache.partition(topic, cluster);
  5. }
  6. // hash the keyBytes to choose a partition
  7. return Utils.toPositive(Utils.murmur2(keyBytes)) % numPartitions;
  8. }

5.批次添加处理

如果第一次添加会为分区初始化一个双端队列,然后获取批次为空会

ProducerBatch batch = new ProducerBatch(tp, recordsBuilder, nowMs)创建一个新的批次放到队列中dq.addLast(batch);

  1. public RecordAppendResult append(TopicPartition tp,
  2. long timestamp,
  3. byte[] key,
  4. byte[] value,
  5. Header[] headers,
  6. Callback callback,
  7. long maxTimeToBlock,
  8. boolean abortOnNewBatch,
  9. long nowMs) throws InterruptedException {
  10. // We keep track of the number of appending thread to make sure we do not miss batches in
  11. // abortIncompleteBatches().
  12. appendsInProgress.incrementAndGet();
  13. ByteBuffer buffer = null;
  14. if (headers == null) headers = Record.EMPTY_HEADERS;
  15. try {
  16. // check if we have an in-progress batch
  17. Deque<ProducerBatch> dq = getOrCreateDeque(tp);
  18. synchronized (dq) {
  19. if (closed)
  20. throw new KafkaException("Producer closed while send in progress");
  21. RecordAppendResult appendResult = tryAppend(timestamp, key, value, headers, callback, dq, nowMs);
  22. if (appendResult != null)
  23. return appendResult;
  24. }
  25. // we don't have an in-progress record batch try to allocate a new batch
  26. if (abortOnNewBatch) {
  27. // Return a result that will cause another call to append.
  28. return new RecordAppendResult(null, false, false, true);
  29. }
  30. byte maxUsableMagic = apiVersions.maxUsableProduceMagic();
  31. int size = Math.max(this.batchSize, AbstractRecords.estimateSizeInBytesUpperBound(maxUsableMagic, compression, key, value, headers));
  32. log.trace("Allocating a new {} byte message buffer for topic {} partition {} with remaining timeout {}ms", size, tp.topic(), tp.partition(), maxTimeToBlock);
  33. // 内存池中分配内存
  34. buffer = free.allocate(size, maxTimeToBlock);
  35. // Update the current time in case the buffer allocation blocked above.
  36. nowMs = time.milliseconds();
  37. synchronized (dq) {
  38. // Need to check if producer is closed again after grabbing the dequeue lock.
  39. if (closed)
  40. throw new KafkaException("Producer closed while send in progress");
  41. RecordAppendResult appendResult = tryAppend(timestamp, key, value, headers, callback, dq, nowMs);
  42. if (appendResult != null) {
  43. // Somebody else found us a batch, return the one we waited for! Hopefully this doesn't happen often...
  44. return appendResult;
  45. }
  46. MemoryRecordsBuilder recordsBuilder = recordsBuilder(buffer, maxUsableMagic);
  47. ProducerBatch batch = new ProducerBatch(tp, recordsBuilder, nowMs);
  48. FutureRecordMetadata future = Objects.requireNonNull(batch.tryAppend(timestamp, key, value, headers,
  49. callback, nowMs));
  50. dq.addLast(batch);
  51. incomplete.add(batch);
  52. // Don't deallocate this buffer in the finally block as it's being used in the record batch
  53. buffer = null;
  54. return new RecordAppendResult(future, dq.size() > 1 || batch.isFull(), true, false);
  55. }
  56. } finally {
  57. if (buffer != null)
  58. free.deallocate(buffer);
  59. appendsInProgress.decrementAndGet();
  60. }
  61. }

然后主流程中会再次调用添加,此时有了批次将能够添加成功:

  1. result = accumulator.append(tp, timestamp, serializedKey,
  2. serializedValue, headers, interceptCallback, remainingWaitMs, false, nowMs);

6.发送消息

批次满了或者创建了新的批次将唤醒消息发送线程:

  1. if (result.batchIsFull || result.newBatchCreated) {
  2. log.trace("Waking up the sender since topic {} partition {} is either full or getting a new batch", record.topic(), partition);
  3. this.sender.wakeup();
  4. }

后续将更加深入分析kafka的NIO源码,探究它怎么多到高性能的。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/428599
推荐阅读
相关标签
  

闽ICP备14008679号