Producing Messages
To send messages to a Kafka topic using Java code, you need to use the Kafka Producer API. Here's an example of how to produce a message:
1import org.apache.kafka.clients.producer.Producer;
2import org.apache.kafka.clients.producer.ProducerRecord;
3import org.apache.kafka.clients.producer.KafkaProducer;
4import org.apache.kafka.common.serialization.StringSerializer;
5
6import java.util.Properties;
7
8public class KafkaMessageProducer {
9 public static void main(String[] args) {
10 // Set up producer configuration
11 Properties properties = new Properties();
12 properties.put("bootstrap.servers", "localhost:9092");
13 properties.put("key.serializer", StringSerializer.class.getName());
14 properties.put("value.serializer", StringSerializer.class.getName());
15
16 // Create a new Kafka producer
17 Producer<String, String> producer = new KafkaProducer<>(properties);
18
19 // Create and send a message
20 String topic = "my-topic";
21 String key = "key1";
22 String value = "Hello, Kafka!";
23 ProducerRecord<String, String> record = new ProducerRecord<>(topic, key, value);
24 producer.send(record);
25
26 // Close the producer
27 producer.close();
28 }
29}
In the code example above, we first set up the producer configuration, including the bootstrap.servers
property which specifies the Kafka brokers to connect to. We also specify the key and value serializers for the messages.
Then, we create a new instance of the KafkaProducer class with the configuration properties. We define the topic, key, and value for the message we want to produce.
Finally, we create a ProducerRecord object with the topic, key, and value, and use the send()
method of the producer to send the message to the Kafka topic.
Make sure to close the producer after you're done sending messages.
This is a basic example of how to produce messages to a Kafka topic using Java code. You can customize the producer configuration and message content based on your specific requirements and use cases.
xxxxxxxxxx
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Properties;
public class KafkaMessageProducer {
public static void main(String[] args) {
// Set up producer configuration
Properties properties = new Properties();
properties.put("bootstrap.servers", "localhost:9092");
properties.put("key.serializer", StringSerializer.class.getName());
properties.put("value.serializer", StringSerializer.class.getName());
// Create a new Kafka producer
Producer<String, String> producer = new KafkaProducer<>(properties);
// Create and send a message
String topic = "my-topic";
String key = "key1";
String value = "Hello, Kafka!";
ProducerRecord<String, String> record = new ProducerRecord<>(topic, key, value);
producer.send(record);
// Close the producer
producer.close();
}
}