使用 KafkaTemplate 发送消息
使用 Spring 的 KafkaTemplate 以编程方式向 Kafka 主题发送消息,包括同步和异步方式。
使用 KafkaTemplate 发送消息 是 CoddyKit 上的免费 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Meet Spring's KafkaTemplate
Welcome to sending messages with Spring Boot and Kafka! At the heart of sending messages is Spring's KafkaTemplate.
- It simplifies interacting with Kafka.
- It handles connection management and serialization.
- It lets you send messages to any Kafka topic easily.
Think of it as your primary tool for producing events.
Injecting KafkaTemplate in Spring
To use KafkaTemplate, you simply inject it into your Spring component (like a service or controller). Spring Boot auto-configures it for you, provided you have the spring-kafka dependency.
You just need to declare it, and Spring handles the rest!
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class MyProducerService {
private final KafkaTemplate<String, String> kafkaTemplate;
public MyProducerService(KafkaTemplate<String, String> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
}Sending Your First Message
The simplest way to send a message is using the send() method. You specify the topic name and the message payload.
A topic is a category or feed name where records are stored and published. The payload is the actual data you want to send.
Basic KafkaTemplate Send Example
Here's a complete, runnable Spring Boot application that sends a simple string message to a topic named my-topic. Make sure a Kafka broker is running (e.g., on localhost:9092) for this to work.
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
@SpringBootApplication
public class KafkaProducerApp {
public static void main(String[] args) {
SpringApplication.run(KafkaProducerApp.class, args);
}
@Component
public class MyMessageSender implements CommandLineRunner {
private final KafkaTemplate<String, String> kafkaTemplate;
public MyMessageSender(KafkaTemplate<String, String> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
@Override
public void run(String... args) throws Exception {
String topic = "my-topic";
String message = "Hello from CoddyKit!";
kafkaTemplate.send(topic, message);
System.out.println("Sent message: " + message + " to topic: " + topic);
}
}
}Synchronous Message Sending
By default, kafkaTemplate.send() is asynchronous. However, you can make it synchronous by calling .get() on the returned ListenableFuture.
- This blocks the current thread until the message is sent and acknowledged by Kafka.
- Useful when you need immediate confirmation that a message was processed.
- Can impact performance due to blocking, so use wisely.
import org.springframework.kafka.support.SendResult;
import java.util.concurrent.ExecutionException;
// ... in a service method
try {
SendResult<String, String> result =
kafkaTemplate.send("sync-topic", "Sync message").get();
System.out.println("Message sent synchronously: " +
result.getProducerRecord().value());
} catch (InterruptedException | ExecutionException e) {
System.err.println("Failed to send message: " + e.getMessage());
}Asynchronous Sending: The Preferred Way
For most applications, asynchronous sending is preferred. It allows your application to continue processing without waiting for Kafka's acknowledgment, improving throughput.
send()returns aListenableFuture(orCompletableFuturein newer Spring versions).- You attach callbacks to this future to handle success or failure.
- This non-blocking approach is key for scalable microservices.
Handling Asynchronous Success
To process the result of an asynchronous send, you use callbacks. The success callback receives a SendResult object, which contains details about the sent record.
This is where you'd log successful sends or update application state.
kafkaTemplate.send("async-topic", "Async message")
.addCallback(
result -> System.out.println("Sent successfully: " +
result.getProducerRecord().value()),
ex -> System.err.println("Failed to send: " +
ex.getMessage())
);Handling Asynchronous Failure
The failure callback is crucial for robust applications. It's invoked if the message cannot be sent after retries, or if an immediate error occurs.
In this callback, you should:
- Log the error details.
- Implement retry logic (if not handled by Kafka config).
- Move the message to a Dead Letter Topic (DLT) for later inspection.
Async Send with Callbacks Example
Let's update our previous example to use asynchronous sending with success and failure callbacks. This demonstrates a more robust way to send messages.
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
@SpringBootApplication
public class KafkaAsyncProducerApp {
public static void main(String[] args) {
SpringApplication.run(KafkaAsyncProducerApp.class, args);
}
@Component
public class MyAsyncMessageSender implements CommandLineRunner {
private final KafkaTemplate<String, String> kafkaTemplate;
public MyAsyncMessageSender(KafkaTemplate<String, String> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
@Override
public void run(String... args) throws Exception {
String topic = "my-async-topic";
String message = "Hello async from CoddyKit!";
kafkaTemplate.send(topic, message)
.addCallback(
result -> System.out.println("Async success: " + result.getProducerRecord().value()),
ex -> System.err.println("Async failure: " + ex.getMessage())
);
System.out.println("Attempted to send async message.");
}
}
}Sending with Keys for Ordering
Kafka allows you to send messages with a key. The key is used to determine which partition a message goes to.
- Messages with the same key always go to the same partition.
- This ensures ordering for related messages (e.g., all updates for a specific user).
- Use
kafkaTemplate.send(topic, key, message).
kafkaTemplate.send("user-events", "user-123", "User 123 updated profile");
kafkaTemplate.send("user-events", "user-456", "User 456 logged in");KafkaTemplate Question
Which of the following statements about KafkaTemplate.send() and its return type is TRUE?
Recap: Sending Messages
Great job! You've learned the essentials of sending messages with Spring Boot's KafkaTemplate:
- Injection: How to get
KafkaTemplatein your services. - Basic Send: Using
send(topic, message). - Synchronous: Blocking with
.get()for immediate confirmation. - Asynchronous: The preferred method using
ListenableFutureand callbacks for efficiency. - Keys: How to use message keys for ordering and partitioning.
Next, we'll dive into customizing producer configurations for optimized performance and reliability!
常见问题解答
「使用 KafkaTemplate 发送消息」课时是免费的吗?
是的 — 「使用 KafkaTemplate 发送消息」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课程的其余内容,请升级到 CoddyKit PRO。 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课程共包含 4 节课。
「使用 KafkaTemplate 发送消息」这节课中我会学到什么?
使用 Spring 的 KafkaTemplate 以编程方式向 Kafka 主题发送消息,包括同步和异步方式。 你通过在浏览器中直接运行的动手代码来练习 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) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「使用 KafkaTemplate 发送消息」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课中编写并运行代码吗?
能。每节 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 集成 Spring Kafka Starter
- 使用 KafkaTemplate 发送消息
- 自定义生产者配置
- 处理生产者发送回调与确认