Maven rely on

Copy the code


public class MyProducer {

    private static Producer<String, String> producer;

    public static void init(a) {
        Properties props = new Properties();
        props.put("bootstrap.servers"."localhost:9092, localhost:9093");

        producer = new KafkaProducer<>(props);

    public static void main(String[] args) {

        for (int i = 0; i < 100; i++){
            producer.send(new ProducerRecord<>("my-topic"."test-key:"+ Integer.toString(i), "test-val:"+ Integer.toString(i))); } producer.close(); }}Copy the code


public class MyConsumer {

    static KafkaConsumer<String, String> consumer;
    static final Pattern TOPIC = Pattern.compile("my-topic");

    public static void init(a) {
        Properties properties = new Properties();
        properties.put("bootstrap.servers"."localhost:9092, localhost:9093");

        consumer = new KafkaConsumer<>(properties);

    public static void main(String[] args) {
        try {
            while (true) {
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(100));
                for (ConsumerRecord<String, String> record : records) {
                    System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record .value()); }}}finally{ consumer.close(); }}}Copy the code

Pay attention to the point

1. The bootstrap. The servers configuration

This does not need to specify all brokers in the cluster. Kafka finds information about other brokers in the cluster based on one broker. However, it is best to configure more than one broker in case one fails and to connect to other brokers in the configuration.

2. Server. The properties configuration

Copy the code

Advertised. listeners are advertised to broker addresses provided by ZooKeeper for client connections. If advertised.listeners are not configured, they are sent to producer clients.

“PLAINTEXT” indicates the protocol. Optional values include PLAINTEXT and SSL. Hostname can specify an IP address or use “” to indicate that the IP address is valid for all network interfaces. Note that if you don’t have advertised.listeners, you can use the configurations of listeners to notify message producers and consumers. If have no configuration, then use () returns the value of the, for ipv4, basic is the localhost. The producer will then remain stuck, unresponsive, because your client is connected to instead of the server address you expected.