How to send and receive messages in Kafka?

In Kafka, producers and consumers can be used to send and receive messages.

Send a message:

  1. Firstly, create a producer instance and configure the relevant properties.
  2. transmit()

Receive messages:

  1. Firstly, create a consumer instance and configure the relevant properties.
  2. sign up
  3. conducting a survey
  4. Handle the received messages.

Below is a simple example code demonstrating how to send and receive messages.

send message:

import org.apache.kafka.clients.producer.*;

public class ProducerExample {
    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");

        Producer<String, String> producer = new KafkaProducer<>(props);

        String topic = "my-topic";
        String message = "Hello, Kafka!";

        ProducerRecord<String, String> record = new ProducerRecord<>(topic, message);

        producer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata metadata, Exception exception) {
                if (exception != null) {
                    System.err.println("Failed to send message: " + exception.getMessage());
                } else {
                    System.out.println("Message sent successfully! Offset: " + metadata.offset());
                }
            }
        });

        producer.close();
    }
}

Receive message.

import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.*;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

public class ConsumerExample {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.put("bootstrap.servers", "localhost:9092");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("group.id", "my-group");

        Consumer<String, String> consumer = new KafkaConsumer<>(props);

        String topic = "my-topic";

        consumer.subscribe(Collections.singletonList(topic));

        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(1));

            for (ConsumerRecord<String, String> record : records) {
                System.out.println("Received message: " + record.value());
            }
        }
    }
}

The above code is implemented using a Java client, but you can choose other languages or Kafka client libraries according to your own needs to send and receive messages.

bannerAds