Kafka消息发送线程及网络通信

网络 通信技术 Kafka
回顾一下前面提到的发送消息的时序图,上一节说到了Kafka相关的元数据信息以及消息的封装,消息封装完成之后就开始将消息发送出去,这个任务由Sender线程来实现。

 [[420379]]

回顾一下前面提到的发送消息的时序图,上一节说到了Kafka相关的元数据信息以及消息的封装,消息封装完成之后就开始将消息发送出去,这个任务由Sender线程来实现。

1. Sender线程

找到KafkaProducer这个对象,KafkaProducer的构造函数中有这样几行代码。

  1. this.accumulator = new  
  2. RecordAccumulator(config.getInt(ProducerConfig.BATCH_SIZE_CONFIG), 
  3.         this.totalMemorySize, 
  4.         this.compressionType, 
  5.         config.getLong(ProducerConfig.LINGER_MS_CONFIG), 
  6.         retryBackoffMs, 
  7.         metrics, 
  8.         time); 

构造了RecordAccumulator对象,设置了该对象中每个消息批次的大小、缓冲区大小、压缩格式等等。

紧接着就构建了一个非常重要的组件NetworkClient,用作发送消息的载体。

  1. NetworkClient client = new NetworkClient( 
  2.         new Selector(config.getLong(ProducerConfig.CONNECTIONS_MAX_IDLE_MS_CONFIG), this.metrics, time"producer", channelBuilder), 
  3.         this.metadata, 
  4.         clientId, 
  5.         config.getInt(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION), 
  6.         config.getLong(ProducerConfig.RECONNECT_BACKOFF_MS_CONFIG), 
  7.         config.getInt(ProducerConfig.SEND_BUFFER_CONFIG), 
  8.         config.getInt(ProducerConfig.RECEIVE_BUFFER_CONFIG), 
  9.         this.requestTimeoutMs, time); 

对于构建的NetworkClient,有几个重要的参数要注意一下:

√ connections.max.idle.ms: 表示一个网络连接最多空闲多久,超过这个空闲时间,就关闭这个网络连接,默认是9分钟。

√ max.in.flight.requests.per.connection:表示每个网络连接可以容忍 producer端发送给broker 消息然后消息没有响应的个数,默认是5个。(ps:producer向broker发送数据的时候,其实是存在多个网络连接)

√ send.buffer.bytes:socket发送数据的缓冲区的大小,默认值是128K。

√ receive.buffer.bytes:socket接受数据的缓冲区的大小,默认值是32K。

构建好消息发送的网络通道直到启动Sender线程,用于发送消息。

  1. this.sender = new Sender(client, 
  2.         this.metadata, 
  3.         this.accumulator, 
  4.         config.getInt(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION) == 1, 
  5.         config.getInt(ProducerConfig.MAX_REQUEST_SIZE_CONFIG), 
  6.         (short) parseAcks(config.getString(ProducerConfig.ACKS_CONFIG)), 
  7.         config.getInt(ProducerConfig.RETRIES_CONFIG), 
  8.         this.metrics, 
  9.         new SystemTime(), 
  10.         clientId, 
  11.         this.requestTimeoutMs); 
  12. //默认的线程名前缀为kafka-producer-network-thread,其中clientId是生产者的id 
  13. String ioThreadName = "kafka-producer-network-thread" + (clientId.length() > 0 ? " | " + clientId : ""); 
  14. //创建了一个守护线程,将Sender对象传进去。 
  15. this.ioThread = new KafkaThread(ioThreadName, this.sender, true); 
  16. //启动线程 
  17. this.ioThread.start(); 

看到这里就非常明确了,既然是线程,那么肯定有run()方法,我们重点关注该方法中的实现逻辑,在这里要补充一点值得我们借鉴的线程使用模式,可以看到在创建sender线程后,并没有立即启动sender线程,而且新创建了KafkaThread线程,将sender对象给传进去了,然后再启动KafkaThread线程,相信有不少小伙伴会有疑惑,我们进去KafkaThread这个类看一下其中的内容。

  1. /** 
  2.  * A wrapper for Thread that sets things up nicely 
  3.  */ 
  4. public class KafkaThread extends Thread { 
  5.     private final Logger log = LoggerFactory.getLogger(getClass()); 
  6.     public KafkaThread(final String name, Runnable runnable, boolean daemon) { 
  7.             super(runnable, name); 
  8.             //设置为后台守护线程 
  9.         setDaemon(daemon); 
  10.             setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { 
  11.                 public void uncaughtException(Thread t, Throwable e) { 
  12.                     log.error("Uncaught exception in " + name + ": ", e); 
  13.                 } 
  14.             }); 
  15.     } 

发现KafkaThread线程其实只是启动了一个守护线程,那么这样做的好处是什么呢?答案是可以将业务代码和线程本身解耦,复杂的业务逻辑可以在KafkaThread这样的线程中去实现,这样在代码层面上Sender线程就非常的简洁,可读性也比较高。

先看一下Sender这个对象的构造。

/**

* 主要的功能就是用处理向 Kafka 集群发送生产请求的后台线程,更新元数据信息,以及将消息发送到合适的节点

* The background thread that handles the sending of produce requests to the Kafka cluster. This thread makes metadata

* requests to renew its view of the cluster and then sends produce requests to the appropriate nodes.

  1. public class Sender implements Runnable { 
  2.     private static final Logger log = LoggerFactory.getLogger(Sender.class); 
  3.     //kafka网络通信客户端,主要用于与broker的网络通信 
  4.     private final KafkaClient client; 
  5.     //消息累加器,包含了批量的消息记录 
  6.     private final RecordAccumulator accumulator; 
  7.     //客户端元数据信息 
  8.     private final Metadata metadata; 
  9.     /* the flag indicating whether the producer should guarantee the message order on the broker or not. */ 
  10.     //保证消息的顺序性的标记 
  11.     private final boolean guaranteeMessageOrder; 
  12.     /* the maximum request size to attempt to send to the server */ 
  13.     //对应的配置是max.request.size,代表调用send()方法发送的最大请求大小 
  14.     private final int maxRequestSize; 
  15.     /* the number of acknowledgements to request from the server */ 
  16.     //用于保证消息发送状态,分别有-1,0,1三种选项 
  17.     private final short acks; 
  18.     /* the number of times to retry a failed request before giving up */ 
  19.     //请求失败重试的次数 
  20.     private final int retries; 
  21.     /* the clock instance used for getting the time */ 
  22.     //时间工具,计算时间,没有特殊含义 
  23.     private final Time time
  24.     /* true while the sender thread is still running */ 
  25.     //表示线程状态,true则表示running 
  26.     private volatile boolean running; 
  27.     /* true when the caller wants to ignore all unsent/inflight messages and force close.  */ 
  28.     //强制关闭消息发送的标识,一旦设置为true,则不管消息有没有发送成功都会忽略 
  29.     private volatile boolean forceClose; 
  30.     /* metrics */ 
  31.     //发送指标收集 
  32.     private final SenderMetrics sensors; 
  33.     /* param clientId of the client */ 
  34.     //生产者客户端id 
  35.     private String clientId; 
  36.     /* the max time to wait for the server to respond to the request*/ 
  37.     //请求超时时间 
  38.     private final int requestTimeout; 
  39.     //构造器 
  40.     public Sender(KafkaClient client, 
  41.                   Metadata metadata, 
  42.                   RecordAccumulator accumulator, 
  43.                   boolean guaranteeMessageOrder, 
  44.                   int maxRequestSize, 
  45.                   short acks, 
  46.                   int retries, 
  47.                   Metrics metrics, 
  48.                   Time time
  49.                   String clientId, 
  50.                   int requestTimeout) { 
  51.         this.client = client; 
  52.         this.accumulator = accumulator; 
  53.         this.metadata = metadata; 
  54.         this.guaranteeMessageOrder = guaranteeMessageOrder; 
  55.         this.maxRequestSize = maxRequestSize; 
  56.         this.running = true
  57.         this.acks = acks; 
  58.         this.retries = retries; 
  59.         this.time = time
  60.         this.clientId = clientId; 
  61.         this.sensors = new SenderMetrics(metrics); 
  62.         this.requestTimeout = requestTimeout; 
  63.     } 
  64.     .... 

大概了解完Sender对象的初始化参数之后,开始步入正题,找到Sender对象中的run()方法。

  1. public void run() { 
  2.     log.debug("Starting Kafka producer I/O thread."); 
  3.     //sender线程启动起来了以后就是处于一直运行的状态 
  4.     while (running) { 
  5.         try { 
  6.             //核心代码 
  7.             run(time.milliseconds()); 
  8.         } catch (Exception e) { 
  9.             log.error("Uncaught error in kafka producer I/O thread: ", e); 
  10.         } 
  11.     } 
  12.     log.debug("Beginning shutdown of Kafka producer I/O thread, sending remaining records."); 
  13.     // okay we stopped accepting requests but there may still be 
  14.     // requests in the accumulator or waiting for acknowledgment, 
  15.     // wait until these are completed. 
  16.     while (!forceClose && (this.accumulator.hasUnsent() || this.client.inFlightRequestCount() > 0)) { 
  17.         try { 
  18.             run(time.milliseconds()); 
  19.         } catch (Exception e) { 
  20.             log.error("Uncaught error in kafka producer I/O thread: ", e); 
  21.         } 
  22.     } 
  23.     if (forceClose) { 
  24.         // We need to fail all the incomplete batches and wake up the threads waiting on 
  25.         // the futures. 
  26.         this.accumulator.abortIncompleteBatches(); 
  27.     } 
  28.     try { 
  29.         this.client.close(); 
  30.     } catch (Exception e) { 
  31.         log.error("Failed to close network client", e); 
  32.     } 
  33.     log.debug("Shutdown of Kafka producer I/O thread has completed."); 

以上的run()方法中,出现了两个while判断,本意都是为了保持线程的不间断运行,将消息发送到broker,两处都调用了另外的一个带时间参数的run(xx)重载方法,第一个run(ts)方法是为了将消息缓存区中的消息发送给broker,第二个run(ts)方法会先判断线程是否强制关闭,如果没有强制关闭,则会将消息缓存区中未发送出去的消息发送完毕,然后才退出线程。

/**

* Run a single iteration of sending

*

* @param now

* The current POSIX time in milliseconds

*/

  1. void run(long now) { 
  2.  
  3.     //第一步,获取元数据 
  4.     Cluster cluster = metadata.fetch(); 
  5.     // get the list of partitions with data ready to send 
  6.  
  7.      //第二步,判断哪些partition满足发送条件 
  8.     RecordAccumulator.ReadyCheckResult result = this.accumulator.ready(cluster, now); 
  9.     /** 
  10.      * 第三步,标识还没有拉取到元数据的topic 
  11.      */ 
  12.     if (!result.unknownLeaderTopics.isEmpty()) { 
  13.         // The set of topics with unknown leader contains topics with leader election pending as well as 
  14.         // topics which may have expired. Add the topic again to metadata to ensure it is included 
  15.         // and request metadata update, since there are messages to send to the topic. 
  16.         for (String topic : result.unknownLeaderTopics) 
  17.             this.metadata.add(topic); 
  18.         this.metadata.requestUpdate(); 
  19.     } 
  20.     // remove any nodes we aren't ready to send to 
  21.     Iterator<Node> iter = result.readyNodes.iterator(); 
  22.     long notReadyTimeout = Long.MAX_VALUE; 
  23.     while (iter.hasNext()) { 
  24.         Node node = iter.next(); 
  25.         /** 
  26.          * 第四步,检查与要发送数据的主机的网络是否已经建立好。 
  27.          */ 
  28.          //如果返回的是false 
  29.             if (!this.client.ready(node, now)) { 
  30.                 //移除result 里面要发送消息的主机。 
  31.                 //所以我们会看到这儿所有的主机都会被移除 
  32.             iter.remove(); 
  33.             notReadyTimeout = Math.min(notReadyTimeout, this.client.connectionDelay(node, now)); 
  34.         } 
  35.     } 

/**

* 第五步,有可能我们要发送的partition有很多个,这种情况下,有可能会存在这样的情况

* 部分partition的leader partition分布在同一台服务器上面。

*

*

*/

  1. Map<Integer, List<RecordBatch>> batches = this.accumulator.drain(cluster, 
  2.                                                                      result.readyNodes, 
  3.                                                                      this.maxRequestSize, 
  4.                                                                      now); 
  5.     if (guaranteeMessageOrder) { 
  6.         // Mute all the partitions drained 
  7.         //如果batches空的话,跳过不执行。 
  8.         for (List<RecordBatch> batchList : batches.values()) { 
  9.             for (RecordBatch batch : batchList) 
  10.                 this.accumulator.mutePartition(batch.topicPartition); 
  11.         } 
  12.     } 

/**

* 第六步,处理超时的批次

*

*/

  1. List<RecordBatch> expiredBatches = this.accumulator.abortExpiredBatches(this.requestTimeout, now); 
  2.     // update sensors 
  3.     for (RecordBatch expiredBatch : expiredBatches) 
  4.         this.sensors.recordErrors(expiredBatch.topicPartition.topic(), expiredBatch.recordCount); 
  5.     sensors.updateProduceRequestMetrics(batches); 
  6.     /** 

* 第七步,创建发送消息的请求,以批的形式发送,可以减少网络传输成本,提高吞吐

*/

  1. List<ClientRequest> requests = createProduceRequests(batches, now); 
  2.     // If we have any nodes that are ready to send + have sendable data, poll with 0 timeout so this can immediately 
  3.     // loop and try sending more data. Otherwise, the timeout is determined by nodes that have partitions with data 
  4.     // that isn't yet sendable (e.g. lingering, backing off). Note that this specifically does not include nodes 
  5.     // with sendable data that aren't ready to send since they would cause busy looping. 
  6.     long pollTimeout = Math.min(result.nextReadyCheckDelayMs, notReadyTimeout); 
  7.     if (result.readyNodes.size() > 0) { 
  8.         log.trace("Nodes with data ready to send: {}", result.readyNodes); 
  9.         log.trace("Created {} produce requests: {}", requests.size(), requests); 
  10.         pollTimeout = 0; 
  11.     } 
  12.     //发送请求的操作 
  13.     for (ClientRequest request : requests) 
  14.         //绑定 op_write 
  15.         client.send(request, now); 
  16.  
  17.     // if some partitions are already ready to be sent, the select time would be 0; 
  18.     // otherwise if some partition already has some data accumulated but not ready yet, 
  19.     // the select time will be the time difference between now and its linger expiry time
  20.     // otherwise the select time will be the time difference between now and the metadata expiry time
  21.     /** 

* 第八步,真正执行网络操作的都是这个NetWordClient这个组件

* 包括:发送请求,接受响应(处理响应)

  1. this.client.poll(pollTimeout, now); 

以上的run(long)方法执行过程总结为下面几个步骤:

1. 获取集群元数据信息

2. 调用RecordAccumulator的ready()方法,判断当前时间戳哪些partition是可以进行发送,以及获取partition 的leader partition的元数据信息,得知哪些节点是可以接收消息的

3. 标记还没有拉到元数据的topic,如果缓存中存在标识为unknownLeaderTopics的topic信息,则将这些topic添加到metadata中,然后调用metadata的requestUpdate()方法,请求更新元数据

4. 将不需要接收消息的节点从按步骤而返回的结果中删除,只对准备接收消息的节点readyNode进行遍历,检查与要发送的节点的网络是否已经建立好,不符合发送条件的节点都会从readyNode中移除掉

5. 针对以上建立好网络连接的节点集合,调用RecordAccumulator的drain()方法,得到等待发送的消息批次集合

6. 处理超时发送的消息,调用RecordAccumulator的addExpiredBatches()方法,循环遍历RecordBatch,判断其中的消息是否超时,如果超时则从队列中移除,释放资源空间

7. 创建发送消息的请求,调用createProducerRequest方法,将消息批次封装成ClientRequest对象,因为批次通常是多个的,所以返回一个List集合

8. 调用NetworkClient的send()方法,绑定KafkaChannel的op_write操作

9. 调用NetworkClient的poll()方法拉取元数据信息,建立连接,执行网络请求,接收响应,完成消息发送

以上就是Sender线程对消息以及集群元数据所发生的核心过程。其中就涉及到了另外一个核心组件NetworkClient。

2. NetworkClient

NetworkClient是消息发送的介质,不管是生产者发送消息,还是消费者接收消息,都需要依赖于NetworkClient建立网络连接。同样的,我们先了解NetworkClient的组成部分,主要涉及NIO的一些知识,有兴趣的童鞋可以看看NIO的原理和组成。

  1. /** 
  2.  * A network client for asynchronous request/response network i/o. This is an internal class used to implement the 
  3.  * user-facing producer and consumer clients. 
  4.  * <p> 
  5.  * This class is not thread-safe! 
  6.  */ 
  7. public class NetworkClient implements KafkaClient 
  8.  
  9.     private static final Logger log = LoggerFactory.getLogger(NetworkClient.class); 
  10.     /* the selector used to perform network i/o */ 
  11.     //java NIO  Selector 
  12.     private final Selectable selector; 
  13.     private final MetadataUpdater metadataUpdater; 
  14.     private final Random randOffset; 
  15.     /* the state of each node's connection */ 
  16.     private final ClusterConnectionStates connectionStates; 
  17.     /* the set of requests currently being sent or awaiting a response */ 
  18.     private final InFlightRequests inFlightRequests; 
  19.     /* the socket send buffer size in bytes */ 
  20.     private final int socketSendBuffer; 
  21.     /* the socket receive size buffer in bytes */ 
  22.     private final int socketReceiveBuffer; 
  23.     /* the client id used to identify this client in requests to the server */ 
  24.     private final String clientId; 
  25.     /* the current correlation id to use when sending requests to servers */ 
  26.     private int correlation; 
  27.     /* max time in ms for the producer to wait for acknowledgement from server*/ 
  28.     private final int requestTimeoutMs; 
  29.     private final Time time
  30.     ...... 
  31.     } 

可以看到NetworkClient实现了KafkaClient接口,包括了几个核心类Selectable、MetadataUpdater、ClusterConnectionStates、InFlightRequests。

2.1 Selectable

其中Selectable是实现异步非阻塞网络IO的接口,通过类的注释可以知道Selectable可以使用单个线程来管理多个网络连接,包括读、写、连接等操作,这个和NIO是一致的。

我们先看看Selectable的实现类Selector,是org.apache.kafka.common.network包下的,源码内容比较多,挑相对比较重要的看。

  1. public class Selector implements Selectable { 
  2.     public static final long NO_IDLE_TIMEOUT_MS = -1; 
  3.     private static final Logger log = LoggerFactory.getLogger(Selector.class); 
  4.     //这个对象就是javaNIO里面的Selector 
  5.     //Selector是负责网络的建立,发送网络请求,处理实际的网络IO。 
  6.     //可以算是最核心的一个组件。 
  7.     private final java.nio.channels.Selector nioSelector; 
  8.     //broker 和 KafkaChannel(SocketChnnel)的映射 
  9.     //这儿的kafkaChannel大家暂时可以理解为就是SocketChannel 
  10.     //维护NodeId和KafkaChannel的映射关系 
  11.     private final Map<String, KafkaChannel> channels; 
  12.     //记录已经完成发送的请求 
  13.     private final List<Send> completedSends; 
  14.     //记录已经接收到的,并且处理完了的响应。 
  15.     private final List<NetworkReceive> completedReceives; 
  16.     //已经接收到了,但是还没来得及处理的响应。 
  17.     //一个连接,对应一个响应队列 
  18.     private final Map<KafkaChannel, Deque<NetworkReceive>> stagedReceives; 
  19.     private final Set<SelectionKey> immediatelyConnectedKeys; 
  20.     //没有建立连接或者或者端口连接的主机 
  21.     private final List<String> disconnected; 
  22.     //完成建立连接的主机 
  23.     private final List<String> connected; 
  24.     //建立连接失败的主机。 
  25.     private final List<String> failedSends; 
  26.     private final Time time
  27.     private final SelectorMetrics sensors; 
  28.     private final String metricGrpPrefix; 
  29.     private final Map<String, String> metricTags; 
  30.     //用于创建KafkaChannel的Builder 
  31.     private final ChannelBuilder channelBuilder; 
  32.     private final int maxReceiveSize; 
  33.     private final boolean metricsPerConnection; 
  34.     private final IdleExpiryManager idleExpiryManager; 

发起网络请求的第一步是连接、注册事件、发送、消息处理,涉及几个核心方法

1. 连接connect()方法

  1. /** 
  2.  * Begin connecting to the given address and add the connection to this nioSelector associated with the given id 
  3.  * number. 
  4.  * <p> 
  5.  * Note that this call only initiates the connection, which will be completed on a future {@link #poll(long)} 
  6.  * call. Check {@link #connected()} to see which (if any) connections have completed after a given poll call. 
  7.  * @param id The id for the new connection 
  8.  * @param address The address to connect to 
  9.  * @param sendBufferSize The send buffer for the new connection 
  10.  * @param receiveBufferSize The receive buffer for the new connection 
  11.  * @throws IllegalStateException if there is already a connection for that id 
  12.  * @throws IOException if DNS resolution fails on the hostname or if the broker is down 
  13.  */ 
  14. @Override 
  15. public void connect(String id, InetSocketAddress address, int sendBufferSize, int receiveBufferSize) throws IOException { 
  16.     if (this.channels.containsKey(id)) 
  17.         throw new IllegalStateException("There is already a connection for id " + id); 
  18.     //获取到SocketChannel 
  19.     SocketChannel socketChannel = SocketChannel.open(); 
  20.     //设置为非阻塞的模式 
  21.     socketChannel.configureBlocking(false); 
  22.     Socket socket = socketChannel.socket(); 
  23.     socket.setKeepAlive(true); 
  24.     //设置网络参数,如发送和接收的buffer大小 
  25.     if (sendBufferSize != Selectable.USE_DEFAULT_BUFFER_SIZE) 
  26.         socket.setSendBufferSize(sendBufferSize); 
  27.     if (receiveBufferSize != Selectable.USE_DEFAULT_BUFFER_SIZE) 
  28.         socket.setReceiveBufferSize(receiveBufferSize); 
  29.     //这个的默认值是false,代表要开启Nagle的算法 
  30.     //它会把网络中的一些小的数据包收集起来,组合成一个大的数据包,再进行发送 
  31.     //因为它认为如果网络中有大量的小的数据包在传输则会影响传输效率 
  32.     socket.setTcpNoDelay(true); 
  33.     boolean connected; 
  34.     try { 
  35.         //尝试去服务器去连接,因为这儿非阻塞的 
  36.         //有可能就立马连接成功,如果成功了就返回true 
  37.         //也有可能需要很久才能连接成功,返回false。 
  38.         connected = socketChannel.connect(address); 
  39.     } catch (UnresolvedAddressException e) { 
  40.         socketChannel.close(); 
  41.         throw new IOException("Can't resolve address: " + address, e); 
  42.     } catch (IOException e) { 
  43.         socketChannel.close(); 
  44.         throw e; 
  45.     } 
  46.     //SocketChannel往Selector上注册了一个OP_CONNECT 
  47.     SelectionKey key = socketChannel.register(nioSelector, SelectionKey.OP_CONNECT); 
  48.     //根据SocketChannel封装出一个KafkaChannel 
  49.     KafkaChannel channel = channelBuilder.buildChannel(id, key, maxReceiveSize); 
  50.     //把key和KafkaChannel关联起来 
  51.     //我们可以根据key就找到KafkaChannel 
  52.     //也可以根据KafkaChannel找到key 
  53.     key.attach(channel); 
  54.     //缓存起来 
  55.     this.channels.put(id, channel); 
  56.  
  57.     //如果连接上了 
  58.     if (connected) { 
  59.         // OP_CONNECT won't trigger for immediately connected channels 
  60.         log.debug("Immediately connected to node {}", channel.id()); 
  61.         immediatelyConnectedKeys.add(key); 
  62.         // 取消前面注册 OP_CONNECT 事件。 
  63.         key.interestOps(0); 
  64.     } 

2. 注册register()

  1. /** 
  2.  * Register the nioSelector with an existing channel 
  3.  * Use this on server-side, when a connection is accepted by a different thread but processed by the Selector 
  4.  * Note that we are not checking if the connection id is valid - since the connection already exists 
  5.  */ 
  6. public void register(String id, SocketChannel socketChannel) throws ClosedChannelException { 
  7.     //往自己的Selector上面注册OP_READ事件 
  8.     //这样的话,Processor线程就可以读取客户端发送过来的连接。 
  9.     SelectionKey key = socketChannel.register(nioSelector, SelectionKey.OP_READ); 
  10.     //kafka里面对SocketChannel封装了一个KakaChannel 
  11.     KafkaChannel channel = channelBuilder.buildChannel(id, key, maxReceiveSize); 
  12.     //key和channel 
  13.     key.attach(channel); 
  14.     //所以我们服务端这儿代码跟我们客户端的网络部分的代码是复用的 
  15.     //channels里面维护了多个网络连接。 
  16.     this.channels.put(id, channel); 

3. 发送send()

  1. /** 
  2.  * Queue the given request for sending in the subsequent {@link #poll(long)} calls 
  3.  * @param send The request to send 
  4.  */ 
  5. public void send(Send send) { 
  6.     //获取到一个KafakChannel 
  7.     KafkaChannel channel = channelOrFail(send.destination()); 
  8.     try { 
  9.          //重要方法 
  10.         channel.setSend(send); 
  11.     } catch (CancelledKeyException e) { 
  12.         this.failedSends.add(send.destination()); 
  13.         close(channel); 
  14.     } 

4. 消息处理poll()

  1. @Override 
  2. public void poll(long timeout) throws IOException { 
  3.     if (timeout < 0) 
  4.         throw new IllegalArgumentException("timeout should be >= 0"); 
  5.     //将上一次poll()方法返回的结果清空 
  6.     clear(); 
  7.     if (hasStagedReceives() || !immediatelyConnectedKeys.isEmpty()) 
  8.         timeout = 0; 
  9.     /* check ready keys */ 
  10.     long startSelect = time.nanoseconds(); 
  11.     //从Selector上找到有多少个key注册了,等待I/O事件发生 
  12.     int readyKeys = select(timeout); 
  13.     long endSelect = time.nanoseconds(); 
  14.     this.sensors.selectTime.record(endSelect - startSelect, time.milliseconds()); 
  15.     //上面刚刚确实是注册了一个key 
  16.     if (readyKeys > 0 || !immediatelyConnectedKeys.isEmpty()) { 
  17.         //处理I/O事件,对这个Selector上面的key要进行处理 
  18.         pollSelectionKeys(this.nioSelector.selectedKeys(), false, endSelect); 
  19.         pollSelectionKeys(immediatelyConnectedKeys, true, endSelect); 
  20.     } 
  21.     // 对stagedReceives里面的数据要进行处理 
  22.     addToCompletedReceives(); 
  23.     long endIo = time.nanoseconds(); 
  24.     this.sensors.ioTime.record(endIo - endSelect, time.milliseconds()); 
  25.     // we use the time at the end of select to ensure that we don't close any connections that 
  26.     // have just been processed in pollSelectionKeys 
  27.     //完成处理后,关闭长链接 
  28.     maybeCloseOldestConnection(endSelect); 

5. 处理Selector上面的key

  1. //用来处理OP_CONNECT,OP_READ,OP_WRITE事件,同时负责检测连接状态 
  2. private void pollSelectionKeys(Iterable<SelectionKey> selectionKeys, 
  3.                                boolean isImmediatelyConnected, 
  4.                                long currentTimeNanos) { 
  5.     //获取到所有key 
  6.     Iterator<SelectionKey> iterator = selectionKeys.iterator(); 
  7.     //遍历所有的key 
  8.     while (iterator.hasNext()) { 
  9.         SelectionKey key = iterator.next(); 
  10.         iterator.remove(); 
  11.         //根据key找到对应的KafkaChannel 
  12.         KafkaChannel channel = channel(key); 
  13.         // register all per-connection metrics at once 
  14.         sensors.maybeRegisterConnectionMetrics(channel.id()); 
  15.         if (idleExpiryManager != null
  16.             idleExpiryManager.update(channel.id(), currentTimeNanos); 
  17.         try { 
  18.             /* complete any connections that have finished their handshake (either normally or immediately) */ 
  19.             //处理完成连接和OP_CONNECT的事件 
  20.             if (isImmediatelyConnected || key.isConnectable()) { 
  21.                 //完成网络的连接。 
  22.                 if (channel.finishConnect()) { 
  23.                     //网络连接已经完成了以后,就把这个channel添加到已连接的集合中 
  24.                     this.connected.add(channel.id()); 
  25.                     this.sensors.connectionCreated.record(); 
  26.                     SocketChannel socketChannel = (SocketChannel) key.channel(); 
  27.                     log.debug("Created socket with SO_RCVBUF = {}, SO_SNDBUF = {}, SO_TIMEOUT = {} to node {}"
  28.                             socketChannel.socket().getReceiveBufferSize(), 
  29.                             socketChannel.socket().getSendBufferSize(), 
  30.                             socketChannel.socket().getSoTimeout(), 
  31.                             channel.id()); 
  32.                 } else 
  33.                     continue
  34.             } 
  35.             /* if channel is not ready finish prepare */ 
  36.             //身份认证 
  37.             if (channel.isConnected() && !channel.ready()) 
  38.                 channel.prepare(); 
  39.             /* if channel is ready read from any connections that have readable data */ 
  40.             if (channel.ready() && key.isReadable() && !hasStagedReceive(channel)) { 
  41.                 NetworkReceive networkReceive; 
  42.                 //处理OP_READ事件,接受服务端发送回来的响应(请求) 
  43.                 //networkReceive 代表的就是一个服务端发送回来的响应 
  44.                 while ((networkReceive = channel.read()) != null
  45.                     addToStagedReceives(channel, networkReceive); 
  46.             } 
  47.             /* if channel is ready write to any sockets that have space in their buffer and for which we have data */ 
  48.             //处理OP_WRITE事件 
  49.             if (channel.ready() && key.isWritable()) { 
  50.                 //获取到要发送的那个网络请求,往服务端发送数据 
  51.                 //如果消息被发送出去了,就会移除OP_WRITE 
  52.                 Send send = channel.write(); 
  53.                 //已经完成响应消息的发送 
  54.                 if (send != null) { 
  55.                     this.completedSends.add(send); 
  56.                     this.sensors.recordBytesSent(channel.id(), send.size()); 
  57.                 } 
  58.             } 
  59.             /* cancel any defunct sockets */ 
  60.             if (!key.isValid()) { 
  61.                 close(channel); 
  62.                 this.disconnected.add(channel.id()); 
  63.             } 
  64.         } catch (Exception e) { 
  65.             String desc = channel.socketDescription(); 
  66.             if (e instanceof IOException) 
  67.                 log.debug("Connection with {} disconnected"desc, e); 
  68.             else 
  69.                 log.warn("Unexpected error from {}; closing connection"desc, e); 
  70.             close(channel); 
  71.             //添加到连接失败的集合中 
  72.             this.disconnected.add(channel.id()); 
  73.         } 
  74.     } 

2.2 MetadataUpdater

是NetworkClient用于请求更新集群元数据信息并检索集群节点的接口,是一个非线程安全的内部类,有两个实现类,分别是DefaultMetadataUpdater和ManualMetadataUpdater,NetworkClient用到的是DefaultMetadataUpdater类,是NetworkClient的默认实现类,同时是NetworkClient的内部类,从源码可以看到,如下。

  1. if (metadataUpdater == null) { 
  2.     if (metadata == null
  3.         throw new IllegalArgumentException("`metadata` must not be null"); 
  4.     this.metadataUpdater = new DefaultMetadataUpdater(metadata); 
  5. else { 
  6.     this.metadataUpdater = metadataUpdater; 
  7. ...... 
  8. class DefaultMetadataUpdater implements MetadataUpdater 
  9.     /* the current cluster metadata */ 
  10.     //集群元数据对象 
  11.     private final Metadata metadata; 
  12.     /* true if there is a metadata request that has been sent and for which we have not yet received a response */ 
  13.     //用来标识是否已经发送过MetadataRequest,若是已发送,则无需重复发送 
  14.     private boolean metadataFetchInProgress; 
  15.     /* the last timestamp when no broker node is available to connect */ 
  16.     //记录没有发现可用节点的时间戳 
  17.     private long lastNoNodeAvailableMs; 
  18.     DefaultMetadataUpdater(Metadata metadata) { 
  19.         this.metadata = metadata; 
  20.         this.metadataFetchInProgress = false
  21.         this.lastNoNodeAvailableMs = 0; 
  22.     } 
  23.     //返回集群节点集合 
  24.     @Override 
  25.     public List<Node> fetchNodes() { 
  26.         return metadata.fetch().nodes(); 
  27.     } 
  28.     @Override 
  29.     public boolean isUpdateDue(long now) { 
  30.         return !this.metadataFetchInProgress && this.metadata.timeToNextUpdate(now) == 0; 
  31.     } 
  32.     //核心方法,判断当前集群保存的元数据是否需要更新,如果需要更新则发送MetadataRequest请求 
  33.     @Override 
  34.     public long maybeUpdate(long now) { 
  35.         // should we update our metadata? 
  36.         //获取下次更新元数据的时间戳 
  37.         long timeToNextMetadataUpdate = metadata.timeToNextUpdate(now); 
  38.         //获取下次重试连接服务端的时间戳 
  39.         long timeToNextReconnectAttempt = Math.max(this.lastNoNodeAvailableMs + metadata.refreshBackoff() - now, 0); 
  40.         //检测是否已经发送过MetadataRequest请求 
  41.         long waitForMetadataFetch = this.metadataFetchInProgress ? Integer.MAX_VALUE : 0; 
  42.         // if there is no node available to connect, back off refreshing metadata 
  43.         long metadataTimeout = Math.max(Math.max(timeToNextMetadataUpdate, timeToNextReconnectAttempt), 
  44.                 waitForMetadataFetch); 
  45.         if (metadataTimeout == 0) { 
  46.             // Beware that the behavior of this method and the computation of timeouts for poll() are 
  47.             // highly dependent on the behavior of leastLoadedNode. 
  48.             //找到负载最小的节点 
  49.             Node node = leastLoadedNode(now); 
  50.             // 创建MetadataRequest请求,待触发poll()方法执行真正的发送操作。 
  51.             maybeUpdate(now, node); 
  52.         } 
  53.         return metadataTimeout; 
  54.     } 
  55.     //处理没有建立好连接的请求 
  56.     @Override 
  57.     public boolean maybeHandleDisconnection(ClientRequest request) { 
  58.         ApiKeys requestKey = ApiKeys.forId(request.request().header().apiKey()); 
  59.         if (requestKey == ApiKeys.METADATA && request.isInitiatedByNetworkClient()) { 
  60.             Cluster cluster = metadata.fetch(); 
  61.             if (cluster.isBootstrapConfigured()) { 
  62.                 int nodeId = Integer.parseInt(request.request().destination()); 
  63.                 Node node = cluster.nodeById(nodeId); 
  64.                 if (node != null
  65.                     log.warn("Bootstrap broker {}:{} disconnected", node.host(), node.port()); 
  66.             } 
  67.             metadataFetchInProgress = false
  68.             return true
  69.         } 
  70.         return false
  71.     } 
  72.     //解析响应信息 
  73.     @Override 
  74.     public boolean maybeHandleCompletedReceive(ClientRequest req, long now, Struct body) { 
  75.         short apiKey = req.request().header().apiKey(); 
  76.         //检查是否为MetadataRequest请求 
  77.         if (apiKey == ApiKeys.METADATA.id && req.isInitiatedByNetworkClient()) { 
  78.             // 处理响应 
  79.             handleResponse(req.request().header(), body, now); 
  80.             return true
  81.         } 
  82.         return false
  83.     } 
  84.     @Override 
  85.     public void requestUpdate() { 
  86.         this.metadata.requestUpdate(); 
  87.     } 
  88.     //处理MetadataRequest请求响应 
  89.     private void handleResponse(RequestHeader header, Struct body, long now) { 
  90.         this.metadataFetchInProgress = false
  91.         //因为服务端发送回来的是一个二进制的数据结构 
  92.         //所以生产者这儿要对这个数据结构要进行解析 
  93.         //解析完了以后就封装成一个MetadataResponse对象。 
  94.         MetadataResponse response = new MetadataResponse(body); 
  95.         //响应里面会带回来元数据的信息 
  96.         //获取到了从服务端拉取的集群的元数据信息。 
  97.         Cluster cluster = response.cluster(); 
  98.         // check if any topics metadata failed to get updated 
  99.         Map<String, Errors> errors = response.errors(); 
  100.         if (!errors.isEmpty()) 
  101.             log.warn("Error while fetching metadata with correlation id {} : {}", header.correlationId(), errors); 
  102.         // don't update the cluster if there are no valid nodes...the topic we want may still be in the process of being 
  103.         // created which means we will get errors and no nodes until it exists 
  104.         //如果正常获取到了元数据的信息 
  105.         if (cluster.nodes().size() > 0) { 
  106.             //更新元数据信息。 
  107.             this.metadata.update(cluster, now); 
  108.         } else { 
  109.             log.trace("Ignoring empty metadata response with correlation id {}.", header.correlationId()); 
  110.             this.metadata.failedUpdate(now); 
  111.         } 
  112.     } 
  113.     /** 
  114.      * Create a metadata request for the given topics 
  115.      */ 
  116.     private ClientRequest request(long now, String node, MetadataRequest metadata) { 
  117.         RequestSend send = new RequestSend(node, nextRequestHeader(ApiKeys.METADATA), metadata.toStruct()); 
  118.         return new ClientRequest(now, true, send, nulltrue); 
  119.     } 
  120.     /** 
  121.      * Add a metadata request to the list of sends if we can make one 
  122.      */ 
  123.     private void maybeUpdate(long now, Node node) { 
  124.     //检测node是否可用 
  125.         if (node == null) { 
  126.             log.debug("Give up sending metadata request since no node is available"); 
  127.             // mark the timestamp for no node available to connect 
  128.             this.lastNoNodeAvailableMs = now; 
  129.             return
  130.         } 
  131.         String nodeConnectionId = node.idString(); 
  132.         //判断网络连接是否应建立好,是否可用向该节点发送请求 
  133.         if (canSendRequest(nodeConnectionId)) { 
  134.             this.metadataFetchInProgress = true
  135.             MetadataRequest metadataRequest; 
  136.             //指定需要更新元数据的topic 
  137.             if (metadata.needMetadataForAllTopics()) 
  138.                 //封装请求(获取所有topics)的元数据信息的请求 
  139.                 metadataRequest = MetadataRequest.allTopics(); 
  140.             else 
  141.              //我们默认走的这儿的这个方法 
  142.             //就是拉取我们发送消息的对应的topic的方法 
  143.                 metadataRequest = new MetadataRequest(new ArrayList<>(metadata.topics())); 
  144.             //这儿就给我们创建了一个请求(拉取元数据的) 
  145.             ClientRequest clientRequest = request(now, nodeConnectionId, metadataRequest); 
  146.             log.debug("Sending metadata request {} to node {}", metadataRequest, node.id()); 
  147.             //缓存请求,待下次触发poll()方法执行发送操作 
  148.             doSend(clientRequest, now); 
  149.         } else if (connectionStates.canConnect(nodeConnectionId, now)) { 
  150.             // we don't have a connection to this node right now, make one 
  151.             log.debug("Initialize connection to node {} for sending metadata request", node.id()); 
  152.             //初始化连接 
  153.             initiateConnect(node, now); 
  154.             // If initiateConnect failed immediately, this node will be put into blackout and we 
  155.             // should allow immediately retrying in case there is another candidate node. If it 
  156.             // is still connecting, the worst case is that we end up setting a longer timeout 
  157.             // on the next round and then wait for the response. 
  158.         } else { // connected, but can't send more OR connecting 
  159.             // In either case, we just need to wait for a network event to let us know the selected 
  160.             // connection might be usable again. 
  161.             this.lastNoNodeAvailableMs = now; 
  162.         } 
  163.     } 
  164. 将ClientRequest请求缓存到InFlightRequest缓存队列中。 
  165. private void doSend(ClientRequest request, long now) { 
  166.     request.setSendTimeMs(now); 
  167.     //这儿往inFlightRequests缓存队列里面还没有收到响应的请求,默认最多能存5个请求 
  168.     this.inFlightRequests.add(request); 
  169.     //然后不断调用Selector的send()方法 
  170.     selector.send(request.request()); 

2.3 InFlightRequests

这个类是一个请求队列,用于缓存已经发送出去但是没有收到响应的ClientRequest,提供了许多管理缓存队列的方法,支持通过配置参数控制ClientRequest的数量,通过源码可以看到其底层数据结构Map。

  1. /** 
  2.  * The set of requests which have been sent or are being sent but haven't yet received a response 
  3.  */ 
  4. final class InFlightRequests { 
  5.     private final int maxInFlightRequestsPerConnection; 
  6.     private final Map<String, Deque<ClientRequest>> requests = new HashMap<>(); 
  7.     public InFlightRequests(int maxInFlightRequestsPerConnection) { 
  8.         this.maxInFlightRequestsPerConnection = maxInFlightRequestsPerConnection; 
  9.     } 
  10. ...... 

除了包含了很多关于处理队列的方法之外,有一个比较重要的方法着重看一下canSendMore()。

  1. /** 
  2.  * Can we send more requests to this node? 
  3.  * 
  4.  * @param node Node in question 
  5.  * @return true iff we have no requests still being sent to the given node 
  6.  */ 
  7. public boolean canSendMore(String node) { 
  8.     //获得要发送到节点的ClientRequest队列 
  9.     Deque<ClientRequest> queue = requests.get(node); 
  10.     //如果节点出现请求堆积,未及时处理,则有可能出现请求超时的情况 
  11.     return queue == null || queue.isEmpty() || 
  12.            (queue.peekFirst().request().completed() 
  13.            && queue.size() < this.maxInFlightRequestsPerConnection); 

了解完上面几个核心类之后,我们开始剖析NetworkClient的流程和实现。

2.4 NetworkClient

Kafka中所有的消息都都需要借助NetworkClient与上下游建立发送通道,其重要性不言而喻。这里我们只考虑消息成功的流程,异常处理不做解析,相对而言没那么重要,消息发送的流程大致如下:

1. 首先调用ready()方法,判断节点是否具备发送消息的条件

2. 通过isReady()方法判断是否可以往节点发送更多请求,用来检查是否有请求堆积

3. 使用initiateConnect初始化连接

4. 然后调用selector的connect()方法建立连接

5. 获取SocketChannel,与服务端建立连接

6. SocketChannel往Selector注册OP_CONNECT事件

7. 调用send()方式发送请求

8. 调用poll()方法处理请求

下面就根据消息发送流程涉及的核心方法进行剖析,了解每个流程中涉及的主要操作。

1. 检查节点是否满足消息发送条件

  1. /** 
  2.  * Begin connecting to the given node, return true if we are already connected and ready to send to that node. 
  3.  * 
  4.  * @param node The node to check 
  5.  * @param now The current timestamp 
  6.  * @return True if we are ready to send to the given node 
  7.  */ 
  8. @Override 
  9. public boolean ready(Node node, long now) { 
  10.     if (node.isEmpty()) 
  11.         throw new IllegalArgumentException("Cannot connect to empty node " + node); 
  12.     //判断要发送消息的主机,是否具备发送消息的条件 
  13.     if (isReady(node, now)) 
  14.         return true
  15.     //判断是否可以尝试去建立网络 
  16.     if (connectionStates.canConnect(node.idString(), now)) 
  17.         // if we are interested in sending to a node and we don't have a connection to it, initiate one 
  18.         //初始化连接 
  19.         //绑定了 连接到事件而已 
  20.         initiateConnect(node, now); 
  21.     return false

2. 初始化连接

  1. /** 
  2.  * Initiate a connection to the given node 
  3.  */ 
  4. private void initiateConnect(Node node, long now) { 
  5.     String nodeConnectionId = node.idString(); 
  6.     try { 
  7.         log.debug("Initiating connection to node {} at {}:{}.", node.id(), node.host(), node.port()); 
  8.         this.connectionStates.connecting(nodeConnectionId, now); 
  9.         //开始建立连接 
  10.         selector.connect(nodeConnectionId, 
  11.                          new InetSocketAddress(node.host(), node.port()), 
  12.                          this.socketSendBuffer, 
  13.                          this.socketReceiveBuffer); 
  14.     } catch (IOException e) { 
  15.         /* attempt failed, we'll try again after the backoff */ 
  16.         connectionStates.disconnected(nodeConnectionId, now); 
  17.         /* maybe the problem is our metadata, update it */ 
  18.         metadataUpdater.requestUpdate(); 
  19.         log.debug("Error connecting to node {} at {}:{}:", node.id(), node.host(), node.port(), e); 
  20.     } 

3. initiateConnect()方法中调用的connect()方法就是Selectable实现类Selector的connect()方法,包括获取SocketChannel并注册OP_CONNECT、OP_READ、 OP_WRITE事件上面已经分析了,这里不做赘述,完成以上一系列建立网络连接的动作之后将消息请求发送到下游节点,Sender的send()方法会调用NetworkClient的send()方法进行发送,而NetworkClient的send()方法最终调用了Selector的send()方法。

  1. /** 
  2.  * Queue up the given request for sending. Requests can only be sent out to ready nodes. 
  3.  * 
  4.  * @param request The request 
  5.  * @param now The current timestamp 
  6.  */ 
  7. @Override 
  8. public void send(ClientRequest request, long now) { 
  9.     String nodeId = request.request().destination(); 
  10.     //判断已经建立连接状态的节点能否接收更多请求 
  11.     if (!canSendRequest(nodeId)) 
  12.         throw new IllegalStateException("Attempt to send a request to node " + nodeId + " which is not ready."); 
  13.     //发送ClientRequest 
  14.     doSend(request, now); 
  15. private void doSend(ClientRequest request, long now) { 
  16.     request.setSendTimeMs(now); 
  17.     //缓存请求 
  18.     this.inFlightRequests.add(request); 
  19.     selector.send(request.request()); 

4. 最后调用poll()方法处理请求

  1. /** 
  2.  * Do actual reads and writes to sockets. 
  3.  * 
  4.  * @param timeout The maximum amount of time to wait (in ms) for responses if there are none immediately, 
  5.  *                must be non-negative. The actual timeout will be the minimum of timeout, request timeout and 
  6.  *                metadata timeout 
  7.  * @param now The current time in milliseconds 
  8.  * @return The list of responses received 
  9.  */ 
  10. @Override 
  11. public List<ClientResponse> poll(long timeout, long now) { 
  12.     
  13.     //步骤一:请求更新元数据 
  14.     long metadataTimeout = metadataUpdater.maybeUpdate(now); 
  15.     try { 
  16.   
  17.         //步骤二:执行I/O操作,发送请求 
  18.         this.selector.poll(Utils.min(timeout, metadataTimeout, requestTimeoutMs)); 
  19.     } catch (IOException e) { 
  20.         log.error("Unexpected error during I/O", e); 
  21.     } 
  22.     // process completed actions 
  23.     long updatedNow = this.time.milliseconds(); 
  24.     List<ClientResponse> responses = new ArrayList<>(); 
  25.     //步骤三:处理各种响应 
  26.     handleCompletedSends(responses, updatedNow); 
  27.     handleCompletedReceives(responses, updatedNow); 
  28.     handleDisconnections(responses, updatedNow); 
  29.     handleConnections(); 
  30.     handleTimedOutRequests(responses, updatedNow); 
  31.     // invoke callbacks 
  32.     //循环调用ClientRequest的callback回调函数 
  33.     for (ClientResponse response : responses) { 
  34.         if (response.request().hasCallback()) { 
  35.             try { 
  36.                 response.request().callback().onComplete(response); 
  37.             } catch (Exception e) { 
  38.                 log.error("Uncaught error in request completion:", e); 
  39.             } 
  40.         } 
  41.     } 
  42.     return responses; 

有兴趣的童鞋可以继续深究回调函数的逻辑和Selector的操作。

补充说明:

上面有一个点没有涉及到,就是kafka的内存池,可以去看一下BufferPool这个类,这一块知识点应该是要在上一篇文章说的,突然想起来漏掉了,在这里做一下补充,对应就是我们前面说到的RecordAccumulator这个类的数据结构,封装好RecordAccumulator对象是有多个Dqueue组成,每个Dqueue由多个RecordBatch组成,除此之外,RecordAccumulator还包括了BufferPool内存池,这里再稍微回忆一下,RecordAccumulator类初始化了ConcurrentMap。

  1. public final class RecordAccumulator { 
  2. ...... 
  3. private final BufferPool free
  4. ...... 
  5. private final ConcurrentMap<TopicPartition, Deque<RecordBatch>> batches; 

如图所示,我们重点关于内存的分配allocate()和释放deallocate()这个两个方法,有兴趣的小伙伴可以私底下看一下,这个类的代码总共也就三百多行,内容不是很多,欢迎一起交流学习,这里就不做展开了,免得影响本文的主题。

3. 小结

本文主要是剖析Kafka生产者发送消息的真正执行者Sender线程以及作为消息上下游的传输通道NetworkClient组件,主要涉及到NIO的应用,同时介绍了发送消息主要涉及的核心依赖类。写这篇文章主要是起到一个承上启下的作用,既是对前面分析Kafka生产者发送消息的补充,同时也为接下来剖析消费者消费上游消息作铺垫,写得有点不成体系,写文章的思路主要考虑用总分的思路作为线索去分析,个人觉得篇幅过长不方便阅读,所以会尽量精简,重点分析核心方法和流程,希望对读者有所帮助。

 

责任编辑:武晓燕 来源: 数据与智能
相关推荐

2023-03-15 08:17:27

Kafka网络通信组件

2020-11-12 08:52:16

Python

2009-08-24 17:20:13

C#网络通信TCP连接

2019-04-29 10:26:49

TCP网络协议网络通信

2022-12-13 08:39:53

Kafka存储检索

2024-02-20 19:53:57

网络通信协议

2022-12-05 09:25:17

Kubernetes网络模型网络通信

2010-06-09 11:31:55

网络通信协议

2016-08-25 11:17:16

CaaS华为

2022-05-13 10:59:14

容器网络通信

2009-10-16 08:48:08

2010-04-22 16:10:48

Aix操作系统网络通信

2019-09-25 08:25:49

RPC网络通信

2014-09-16 17:00:02

UDP

2010-06-14 19:13:28

网络通信协议

2010-06-29 10:15:31

局域网故障

2021-08-13 11:27:25

网络通信数据

2010-06-09 11:57:42

网络通信协议

2020-07-06 07:52:10

Kubernetes网络通信

2010-07-01 15:45:22

网络通信协议
点赞
收藏

51CTO技术栈公众号