ConsumerNetworkClient解析
开篇
通过消费者第一篇KafkaConsumer解析,我们可以知道,client主要做了两件事情:
- maybeTriggerWakeup() 安全的唤醒消费者客户端
- poll() 轮询任何网络IO
ConsumerNetworkClient 概述
根据名字我们也能看出,此类是消费者访问网路客户端。
官方定义:
- 更高级别的消费者访问网络层。
- 该类是线程安全的,但不提供响应回调的同步。这保证在调用锁时不会持有锁。
说白了就是处理网络IO的类。
成员变量
private static final int MAX_POLL_TIMEOUT_MS = 5000; // 允许的最大超时时间
// the mutable state of this class is protected by the object's monitor (excluding the wakeup
// flag and the request completion queue below).
private final Logger log;
private final KafkaClient client; // kafka客户端
private final UnsentRequests unsent = new UnsentRequests();
private final Metadata metadata; // 元数据类
private final Time time;
private final long retryBackoffMs;
private final int maxPollTimeoutMs;
private final int requestTimeoutMs;
private final AtomicBoolean wakeupDisabled = new AtomicBoolean(); // 执行不可中断方法的标志
// We do not need high throughput, so use a fair lock to try to avoid starvation
private final ReentrantLock lock = new ReentrantLock(true);
// when requests complete, they are transferred to this queue prior to invocation. The purpose
// is to avoid invoking them while holding this object's monitor which can open the door for deadlocks.
// 当请求完成时,它们在调用之前被传输到这个队列。这样做的目的是避免在持有此对象的监视器时调用它们,因为该对象的监视器会打开死锁。
private final ConcurrentLinkedQueue<RequestFutureCompletionHandler> pendingCompletion = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedQueue<Node> pendingDisconnects = new ConcurrentLinkedQueue<>();
// this flag allows the client to be safely woken up without waiting on the lock above. It is
// atomic to avoid the need to acquire the lock above in order to enable it concurrently.
private final AtomicBoolean wakeup = new AtomicBoolean(false);
成员变量不多,也挺简单,接下来看下内部类和内部接口
内部类和内部接口
它拥有两个内部类和一个内部接口。第一次见到内部接口,挺期待呢。
RequestFutureCompletionHandler 内部类
此类主要作用就是记录请求过程中的异常和请求完成之后的结果。
private class RequestFutureCompletionHandler implements RequestCompletionHandler {
private final RequestFuture<ClientResponse> future; // 异步请求结果
private ClientResponse response; // 客户端响应结果
private RuntimeException e; // 运行时异常
private RequestFutureCompletionHandler() {
this.future = new RequestFuture<>();
}
public void fireCompletion() {
//判断有无运行时异常
if (e != null) {
future.raise(e);
// 判断有无身份认证异常
} else if (response.authenticationException() != null) {
future.raise(response.authenticationException());
// 判断有无断开连接异常
} else if (response.wasDisconnected()) {
log.debug("Cancelled request with header {} due to node {} being disconnected",
response.requestHeader(