Kafka生产者初始化逻辑分析

Kafka 生产者流程

在这里插入图片描述
Kafka的主要流程如图:
首先是创建KafkaProducer对象,该对象初始化拦截器用于对消息的过滤,同时也会初始化序列化器,用于对消息的kv对分别进行序列化数据,再之后会初始化分区(可以接受用户自定义传入)用于计算发送的消息应该在那个分区节点上,针对kafka发送的消息并不是直接传输到服务端,而是先一开始缓存起来,针对一个topic会有很多歌分区(比如256),那么针对这256个分区会有256个对列,每个对列存放着一批批的消息Record,KafkaProducer初始化的时候会初始化一个Sender线程,这个线程会不断从RecordAccumulator里面拉数据消息,封装一层转化成ClienttRequest,然后这些Request会统一有NetworkClient进行处理,通过KafkaChannel(NIO机制)来跟服务器对接处理网络请求。

Kafka官方的一个demo

kafka官方demo引入了kafka的一个使用案例,我们来查看发送消息的主要的一个代码段。

package kafka.examples;

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;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

public class Producer extends Thread {
    private final KafkaProducer<Integer, String> producer;
    private final String topic;
    private final Boolean isAsync;

    /**
     * 构建方法,初始化生产者对象
     * @param topic
     * @param isAsync
     */
    public Producer(String topic, Boolean isAsync) {
        Properties props = new Properties();
        // 用户拉取kafka的元数据
        props.put("bootstrap.servers", "hadoop1:9092");
        props.put("client.id", "DemoProducer");
        //设置序列化的类。
        //二进制的格式
        props.put("key.serializer", "org.apache.kafka.common.serialization.IntegerSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        //消费者,消费数据的时候,就需要进行反序列化。
        //TODO 初始化kafkaProducer
        producer = new KafkaProducer<>(props);
        this.topic = topic;
        this.isAsync = isAsync;
    }

    public void run() {
        int messageNo = 1;
        // 一直会往kafka发送数据
        while (true) {
            String messageStr = "Message_" + messageNo;
            long startTime = System.currentTimeMillis();
            //isAsync , kafka发送数据的时候,有两种方式
            //1: 异步发送
            //2: 同步发送
            //isAsync: true的时候是异步发送,false就是同步发送
            if (isAsync) { // Send asynchronously
                //异步发送,一直发送,消息响应结果交给回调函数处理
                //这样的方式,性能比较好,我们生产代码用的就是这种方式。
                producer.send(new ProducerRecord<>(topic,
                    messageNo,
                    messageStr), new DemoCallBack(startTime, messageNo, messageStr));
            } else { // Send synchronously
                try {
                    //同步发送
                    //发送一条消息,等这条消息所有的后续工作都完成以后才继续下一条消息的发送。
                    producer.send(new ProducerRecord<>(topic,
                        messageNo,
                        messageStr)).get();
                    System.out.println("Sent message: (" + messageNo + ", " + messageStr + ")");
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            }
            ++messageNo;
        }
    }
}

class DemoCallBack implements Callback {

    private final long startTime;
    private final int key;
    private final String message;

    public DemoCallBack(long startTime, int key, String message) {
        this.startTime = startTime;
        this.key = key;
        this.message = message;
    }

    /**
     * A callback method the user can implement to provide asynchronous handling of request completion. This method will
     * be called when the record sent to the server has been acknowledged. Exactly one of the arguments will be
     * non-null.
     *
     * @param metadata  The metadata for the record that was sent (i.e. the partition and offset). Null if an error
     *                  occurred.
     * @param exception The exception thrown during processing of this record. Null if no error occurred.
     */
    public void onCompletion(RecordMetadata metadata, Exception exception) {
        long elapsedTime = System.currentTimeMillis() - startTime;

        if(exception != null){
            System.out.println("有异常");
            //一般我们生产里面 还会有其它的备用的链路。
        }else{
            System.out.println("说明没有异常信息,成功的!!");
        }
        if (metadata != null) {
            System.out.println(
                "message(" + key + ", " + message + ") sent to partition(" + metadata.partition() +
                    "), " +
                    "offset(" + metadata.offset() + ") in " + elapsedTime + " ms");
        } else {
            exception.printStackTrace();
        }
    }
}

其中kafka的使用及其简单,有同步异步之分,同步实际上上也是底层异步实现,异步返回的是一个Future对象,通过Future的get操作来实现同步。简介的那个用法就是

producer.send(new ProducerRecord<>(topic,
                    messageNo,
                    messageStr), new DemoCallBack(startTime, messageNo, messageStr));

KafkaProducer的初始化

针对Kafka生产者第一块需要学习的内容就是它是怎么初始化的,以及初始化的时候初始化了哪些东西。
KafkaProducer构造函数内容较多,这里逐一说明一下重点的。

重点类的初始化

(1) 配置一些用户自定义的参数

// 配置一些用户自定义的参数
Map<String, Object> userProvidedConfigs = config.originals();

上述demo, 配置的就是这些东西:

Properties props = new Properties();
        // 用户拉取kafka的元数据
        props.put("bootstrap.servers", "hadoop1:9092");
        props.put("client.id", "DemoProducer");
        //设置序列化的类。
        //二进制的格式
        props.put("key.serializer", "org.apache.kafka.common.serialization.IntegerSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

(2) 分区器

this.partitioner = config.getConfiguredInstance(ProducerConfig.PARTITIONER_CLASS_CONFIG, Partitioner.class);


public <T> T getConfiguredInstance(String key, Class<T> t) {
        Class<?> c = getClass(key);
        if (c == null)
            return null;
        Object o = Utils.newInstance(c);
        if (!t.isInstance(o))
            throw new KafkaException(c.getName() + " is not an instance of " + t.getName());
        if (o instanceof Configurable)
            ((Configurable) o).configure(originals());
        return t.cast(o);
    }

创建分区器,如果用户制定了分区器,那么则根据反射初始化它的对象实例,如果未指定则使用系统默认的分区器(Class 是 DefaultPartitioner)

 .define(PARTITIONER_CLASS_CONFIG,
                                        Type.CLASS,
                                        DefaultPartitioner.class,
                                        Importance.MEDIUM, PARTITIONER_CLASS_DOC)

(3) 设置序列化器,分为key序列化器和value序列化器

 //设置序列化器
            if (keySerializer == null) {
                this.keySerializer = config.getConfiguredInstance(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
                        Serializer.class);
                this.keySerializer.configure(config.originals(), true);
            } else {
                config.ignore(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG);
                this.keySerializer = keySerializer;
            }
            if (valueSerializer == null) {
                this.valueSerializer = config.getConfiguredInstance(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
                        Serializer.class);
                this.valueSerializer.configure(config.originals(), false);
            } else {
                config.ignore(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG);
                this.valueSerializer = valueSerializer;
            }

(4) kafka 拦截器
kafka在这里设置了一个拦截器的集合,这个地方稍微有些多余,因为数据可以在之前就做一些过滤操作,无需等到现在。

 List<ProducerInterceptor<K, V>> interceptorList = (List) (new ProducerConfig(userProvidedConfigs)).getConfiguredInstances(ProducerConfig.INTERCEPTOR_CLASSES_CONFIG,
                    ProducerInterceptor.class);
            this.interceptors = interceptorList.isEmpty() ? null : new ProducerInterceptors<>(interceptorList);

(5) 消息缓冲区

 this.accumulator = new RecordAccumulator(config.getInt(ProducerConfig.BATCH_SIZE_CONFIG),
                    this.totalMemorySize,
                    this.compressionType,
                    config.getLong(ProducerConfig.LINGER_MS_CONFIG),
                    retryBackoffMs,
                    metrics,
                    time);

(6) 创建并启动一个Sender线程


this.sender = new Sender(client,
                    this.metadata,
                    this.accumulator,
                    config.getInt(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION) == 1,
                    config.getInt(ProducerConfig.MAX_REQUEST_SIZE_CONFIG),
                    (short) parseAcks(config.getString(ProducerConfig.ACKS_CONFIG)),
                    config.getInt(ProducerConfig.RETRIES_CONFIG),
                    this.metrics,
                    new SystemTime(),
                    clientId,
                    this.requestTimeoutMs);
            String ioThreadName = "kafka-producer-network-thread" + (clientId.length() > 0 ? " | " + clientId : "");

            //创建了一个线程,然后里面传进去了一个sender对象。
            //把业务的代码和关于线程的代码给隔离开来。
            //关于线程的这种代码设计的方式,其实也值得大家积累的。
            this.ioThread = new KafkaThread(ioThreadName, this.sender, true);
            //启动线程。
            this.ioThread.start();

这里需要关注ack这个重要东西
/***
*
* (1) retries:重试的次数
* (2) acks:
* 0:
* producer发送数据到broker后,就完了,没有返回值,不管写成功还是写失败都不管了。
* 1:
* producer发送数据到broker后,数据成功写入leader partition以后返回响应。
* -1:
* producer发送数据到broker后,数据要写入到leader partition里面,并且数据同步到所有的
* follower partition里面以后,才返回响应。
*
*/

(7) 创建一个专门用于处理网络请求的NetworkClient

NetworkClient client = new NetworkClient(
                    new Selector(config.getLong(ProducerConfig.CONNECTIONS_MAX_IDLE_MS_CONFIG), this.metrics, time, "producer", channelBuilder),
                    this.metadata,
                    clientId,
                    config.getInt(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION),
                    config.getLong(ProducerConfig.RECONNECT_BACKOFF_MS_CONFIG),
                    config.getInt(ProducerConfig.SEND_BUFFER_CONFIG),
                    config.getInt(ProducerConfig.RECEIVE_BUFFER_CONFIG),
                    this.requestTimeoutMs, time);

这个NetworkClient构造器需要参数的解释含义
/**
* (1)connections.max.idle.ms: 默认值是9分钟
* 一个网络连接最多空闲多久,超过这个空闲时间,就关闭这个网络连接。
*
* (2)max.in.flight.requests.per.connection:默认是5
* producer向broker发送数据的时候,其实是有多个网络连接。
* 每个网络连接可以忍受 producer端发送给broker 消息然后消息没有响应的个数。
*
*
* 因为kafka有重试机制,所以有可能会造成数据乱序,如果想要保证有序,这个值要把设置为1.
*
* (3)send.buffer.bytes:socket发送数据的缓冲区的大小,默认值是128K
* (4)receive.buffer.bytes:socket接受数据的缓冲区的大小,默认值是32K。
*/

至此KafkaProducer的重点类初始化就在此结束了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值