0Pricing
Advanced Spring Boot 4: Event-Driven Architecture (Kafka) · 课时

自定义生产者配置

探索确认机制、批量大小、linger.ms 和重试次数等各种生产者配置,以优化性能和可靠性。

自定义生产者配置 是 CoddyKit 上的免费 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Customize Producer Settings?

When sending messages to Kafka, default settings might not always be ideal. Customizing your producer's configuration is key to optimizing for specific needs.

You can fine-tune your producer for better performance, increased reliability, or optimized throughput, depending on your application's requirements.

Configuring in Spring Boot

In Spring Boot, Kafka producer properties are typically defined in your application.yml (or .properties) file.

All producer-related settings usually start with the prefix spring.kafka.producer. Spring Boot automatically picks these up to configure your KafkaTemplate.

spring:
  kafka:
    bootstrap-servers: localhost:9092
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.apache.kafka.common.serialization.StringSerializer
      # Custom configurations go here

Acknowledgments (`acks`)

The acks (acknowledgments) property determines the level of durability for messages sent by the producer. It controls how many replicas must acknowledge the write before the producer considers the message sent successfully.

  • acks=0: Producer doesn't wait for any acknowledgment. Fastest, but lowest durability (messages might be lost).
  • acks=1: Producer waits for the leader replica to acknowledge the write. Good balance of durability and speed.
  • acks=all: Producer waits for all in-sync replicas to acknowledge. Highest durability, but slowest.

Setting `acks=all`

For critical messages where data loss is unacceptable, you'd typically set acks to all. This ensures that your message is safely replicated before the producer moves on.

Remember, higher durability often means slightly higher latency.

spring:
  kafka:
    producer:
      acks: all # Ensures high durability
      # Other producer configs

Batching: `batch.size` & `linger.ms`

To improve throughput, Kafka producers don't send every message individually. Instead, they batch multiple messages together.

  • batch.size: The maximum amount of data (in bytes) that will be collected before sending a batch. Default is 16KB.
  • linger.ms: The maximum time (in milliseconds) the producer will wait for more messages to accumulate in a batch. Default is 0ms (send immediately).

These two properties work together: a batch is sent when either batch.size is reached OR linger.ms expires.

Optimizing Batch Settings

Adjusting batch.size and linger.ms can significantly impact performance. Larger batches and longer linger times can increase throughput but also slightly increase latency for individual messages.

Here's how you might configure them for better batching:

spring:
  kafka:
    producer:
      batch-size: 32768 # 32 KB (larger batch)
      linger-ms: 50     # Wait up to 50ms (longer wait)
      # Other producer configs

Retries (`retries`)

What happens if a message fails to send due to a transient network issue or a temporary broker unavailability?

The retries property specifies how many times the producer should re-attempt sending a message that failed due to a potentially recoverable error. This greatly enhances the reliability of your message delivery.

Setting `retries`

Setting a reasonable number of retries helps ensure your messages eventually reach Kafka, even if there are temporary glitches.

It's often combined with delivery.timeout.ms, which defines the total time a producer will wait for a message to be delivered, including retries.

spring:
  kafka:
    producer:
      retries: 5 # Try up to 5 times on failure
      delivery-timeout-ms: 120000 # 2 minutes total timeout
      # Other producer configs

Custom Producer in Action

While Spring Boot handles the underlying Kafka client configuration based on your application.yml, let's see how these properties are set directly in a Java Kafka producer. This helps understand the core mechanism.

This example explicitly configures and uses a Kafka producer:

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import java.util.Properties;

public class CustomProducerDemo {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.put("bootstrap.servers", "localhost:9092");
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        // Custom configurations we discussed
        props.put("acks", "all");
        props.put("batch.size", 32768);
        props.put("linger.ms", 50);
        props.put("retries", 5);

        try (KafkaProducer<String, String> producer = new KafkaProducer<>(props)) {
            producer.send(new ProducerRecord<>("custom-topic", "key1", "Hello from CoddyKit!"));
            producer.send(new ProducerRecord<>("custom-topic", "key2", "Another custom message!"));
            producer.flush(); // Ensure all buffered records are sent
            System.out.println("Messages sent with custom configurations.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Check Your Knowledge

You've learned about several key producer configurations. Let's test your understanding!

Recap: Customizing Producers

Great job! You've explored how to customize your Kafka producers for various needs:

  • acks: Controls message durability.
  • batch.size & linger.ms: Optimize for throughput by batching messages.
  • retries: Enhances reliability by re-sending failed messages.

By understanding and adjusting these properties, you can tailor your Spring Boot Kafka applications to meet specific performance and reliability goals. Next, we'll dive into implementing Kafka consumers!

常见问题解答

「自定义生产者配置」课时是免费的吗?

是的 — 「自定义生产者配置」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课程的其余内容,请升级到 CoddyKit PRO。 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课程共包含 4 节课。

「自定义生产者配置」这节课中我会学到什么?

探索确认机制、批量大小、linger.ms 和重试次数等各种生产者配置,以优化性能和可靠性。 你通过在浏览器中直接运行的动手代码来练习 Advanced Spring Boot 4: Event-Driven Architecture (Kafka),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「自定义生产者配置」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课中编写并运行代码吗?

能。每节 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 集成 Spring Kafka Starter
  2. 使用 KafkaTemplate 发送消息
  3. 自定义生产者配置
  4. 处理生产者发送回调与确认
← 返回 Advanced Spring Boot 4: Event-Driven Architecture (Kafka)