[Get nèng - Kafka] Application Part (XI) - Java Kafka API (multi-threaded producer)

This blog post is to use Kafka API, multi-threaded producers
more advanced usage see my blog Kafka Series
Reference:
https://www.orchome.com/189
https://www.w3cschool.cn/apache_kafka/apache_kafka_workflow .html

I. Introduction

kafka concepts related to the introduction see the official documents and other Bowen
official Chinese document
kafka introductory presentation

Kafka order to improve the throughput, a large amount of data in the case of cutting the message sequence is not required to use multiple threads producers.
Implementation: instantiate an object sharing KafkaProducer in multiple threads. KafkaProducer is thread-safe.

II. To achieve

2.1 introduces dependence

Mainly rely on spring-kafka

 <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit-dep</artifactId>
            <version>4.9</version>
            <scope>test</scope>
        </dependency>
        
        <!-- kafka start -->
        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka_2.11</artifactId>
            <version>0.10.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka-clients</artifactId>
            <version>0.10.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka-streams</artifactId>
            <version>0.10.1.1</version>
        </dependency>
        <!-- kafka end -->

        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.2-beta-5</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>
    </dependencies>

More than 2.2 thread producers

Producer thread KafkaProducerThread.java

import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

/**
 * 生产者线程
 */
public class KafkaProducerThread implements Runnable {

    private KafkaProducer<String, String> producer = null;

    private ProducerRecord<String, String> record = null;

    public KafkaProducerThread(KafkaProducer<String, String> producer, ProducerRecord<String, String> record) {
        this.producer = producer;
        this.record = record;
    }

    @Override
    public void run() {
        producer.send(record, new Callback() {

            @Override
            public void onCompletion(RecordMetadata metaData,
                                     Exception exception) {
                if (null != exception) {// 发送异常记录异常信息
                    System.out.println("Send message exception:" + exception);
                }
                if (null != metaData) {
                    System.out.println(String.format("offset:%s,partition:%s",
                            metaData.offset(), metaData.partition()));
                }
            }

        });
    }

}

Producers MultiThreadProducer.java

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 生产者--多线程
 */
public class MultiThreadProducer {

    public static void main(String[] args) {
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        // 生产者
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(props);

        // 线程池
        ExecutorService executor = Executors.newFixedThreadPool(5);
        ProducerRecord<String, String> record;

        try {
            for (int i = 0; i < 10; i++) {
                record = new ProducerRecord<String, String>("my-topic", Integer.toString(i), Integer.toString(i));
                executor.submit(new KafkaProducerThread(producer, record));
            }

            Thread.sleep(3000);
        } catch (Exception e) {
            System.out.println("Send message exception" + e);
        } finally {
            producer.close();
            executor.shutdown();
        }
    }
}

Detailed parameters, please refer to:
http://www.shixinke.com/java/kafka-configuration
https://blog.csdn.net/xiaozhu_you/article/details/91493258

Source Address

-CLOUD-KAFKA-IT CLIENT : the Spring integration kafka tutorial source code. Bowen in this CSDN kafka series.


Recommended items

CLOUD-IT : IT service management platform, integrated basic services, middleware services, alarm monitoring services.
CLOUD-ACTIVITI6-IT : the Activiti tutorial source code. CSDN Activiti Bowen in this series.
CLOUD-elasticsearch-IT : elasticsearch tutorial source code. CSDN elasticsearch Bowen in this series.
CLOUD-KAFKA-IT : the Spring integration kafka tutorial source code. Bowen in this CSDN kafka series.
-CLOUD-KAFKA-IT CLIENT : Client tutorial source Kafka used to live. Bowen in this CSDN kafka series.

Open source project, continuously updated, the Star ~ like please

Published 160 original articles · won praise 46 · Views 200,000 +

Guess you like

Origin blog.csdn.net/yy756127197/article/details/103904476