Simple implementation of Java Kafka producer

A simple Kafka consumer implemented in Java:

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

public class MyKafkaProducer {
    
    
    private final static String KAFKA_URL = "localhost:9092";	//Kafka的IP地址
    private final static String TOPIC = "test";		            //需要发送的Topic

    public static void main(String[] args) {
    
    
        Properties properties = new Properties();
        properties.put("bootstrap.servers", KAFKA_URL);
        properties.put("acks", "all");
        properties.put("retries", 0);
        properties.put("batch.size", 16384);
        properties.put("linger.ms", 1);
        properties.put("buffer.memory", 33554432);
        properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        Producer<String, String> producer = null;
        try {
    
    
            producer = new KafkaProducer<String, String>(properties);
            String msg = "Hello World!";
            producer.send(new ProducerRecord<String, String>(TOPIC, msg));
        } catch (Exception e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            producer.close();
        }
    }
}

POM depends on:

        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka-clients</artifactId>
            <version>0.9.0.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka_2.11</artifactId>
            <version>0.9.0.0</version>
        </dependency>

Guess you like

Origin blog.csdn.net/michael_f2008/article/details/115325909