kafka客户端中使用了很多的回调方式处理请求。基本思路是将回调函数暂存到ClientRequest中,而ClientRequest会暂存到inFlightRequests中,当返回response的时候,从inFlightRequests中读取对应的ClientRequest,并调用request中的回调函数完成处理。

inFlightRequests是请求和响应处理的桥梁.

1. 接口和抽象类

无论是producer还是consumer,回调函数类都是实现了RequestCompletionHandler接口。

public interface RequestCompletionHandler {
public void onComplete(ClientResponse response);
}

consumer的回调函数类不但实现了RequestCompletionHandler,还继承了RequestFuture。RequestFuture是一个有状态的类,在调用中会设置响应的状态,可以持有RequestFuture的引用,用来判断请求的状态。

public class RequestFuture<T> {

    private boolean isDone = false;
private T value;
private RuntimeException exception;
private List<RequestFutureListener<T>> listeners = new ArrayList<>();
// 省略其他方法
}

2. producer

producer是在sender线程中创建的ClientRequest,如下:

private List<ClientRequest> createProduceRequests(Map<Integer, List<RecordBatch>> collated, long now) {
List<ClientRequest> requests = new ArrayList<ClientRequest>(collated.size());
for (Map.Entry<Integer, List<RecordBatch>> entry : collated.entrySet())
requests.add(produceRequest(now, entry.getKey(), acks, requestTimeout, entry.getValue()));
return requests;
} // 创建request
private ClientRequest produceRequest(long now, int destination, short acks, int timeout, List<RecordBatch> batches) {
Map<TopicPartition, ByteBuffer> produceRecordsByPartition = new HashMap<TopicPartition, ByteBuffer>(batches.size());
final Map<TopicPartition, RecordBatch> recordsByPartition = new HashMap<TopicPartition, RecordBatch>(batches.size());
for (RecordBatch batch : batches) {
TopicPartition tp = batch.topicPartition;
produceRecordsByPartition.put(tp, batch.records.buffer());
recordsByPartition.put(tp, batch);
}
ProduceRequest request = new ProduceRequest(acks, timeout, produceRecordsByPartition);
RequestSend send = new RequestSend(Integer.toString(destination),
this.client.nextRequestHeader(ApiKeys.PRODUCE),
request.toStruct()); // 回调函数
RequestCompletionHandler callback = new RequestCompletionHandler() {
public void onComplete(ClientResponse response) {
handleProduceResponse(response, recordsByPartition, time.milliseconds());
}
}; // 回调函数保存到request中, 然后request被保存到了inFlightRequests
return new ClientRequest(now, acks != 0, send, callback);
}

在NetworkClient#poll(..)最后会处理会调用对应的回调函数

public List<ClientResponse> poll(long timeout, long now) {
long metadataTimeout = metadataUpdater.maybeUpdate(now);
try {
this.selector.poll(Utils.min(timeout, metadataTimeout, requestTimeoutMs));
} catch (IOException e) {
log.error("Unexpected error during I/O", e);
} // process completed actions
long updatedNow = this.time.milliseconds();
List<ClientResponse> responses = new ArrayList<>();
handleCompletedSends(responses, updatedNow);
handleCompletedReceives(responses, updatedNow);
handleDisconnections(responses, updatedNow);
handleConnections();
handleTimedOutRequests(responses, updatedNow); // invoke callbacks
for (ClientResponse response : responses) { // response中封装了request中的回调函数
if (response.request().hasCallback()) {
try {
response.request().callback().onComplete(response); //调用回调函数
} catch (Exception e) {
log.error("Uncaught error in request completion:", e);
}
}
} return responses;
}

3. Consumer

consumer使用回调函数和producer使用方式类似,但是比producer复杂一些。前面说了Consumer的回调函数不但实现了RequestCompletionHandler,还继承了RequestFuture。

public static class RequestFutureCompletionHandler
extends RequestFuture<ClientResponse>
implements RequestCompletionHandler { @Override
public void onComplete(ClientResponse response) {
if (response.wasDisconnected()) {
ClientRequest request = response.request();
RequestSend send = request.request();
ApiKeys api = ApiKeys.forId(send.header().apiKey());
int correlation = send.header().correlationId();
log.debug("Cancelled {} request {} with correlation id {} due to node {} being disconnected",
api, request, correlation, send.destination());
raise(DisconnectException.INSTANCE);
} else {
complete(response); // 关键, complete方法会设置RequestFuture的状态
}
}
}
} public void complete(T value) { // 设置RequestFuture状态
if (isDone)
throw new IllegalStateException("Invalid attempt to complete a request future which is already complete");
this.value = value;
this.isDone = true;
fireSuccess(); // 循环调用RequestFuture中的listeners
} private void fireSuccess() {
for (RequestFutureListener<T> listener : listeners)
listener.onSuccess(value);
} private void fireFailure() {
for (RequestFutureListener<T> listener : listeners)
listener.onFailure(exception);
}

与producer类似,请求被放到一个map中,不过名字是unsent。如下ConsumerNetworkClient#send(..):

public RequestFuture<ClientResponse> send(Node node,
ApiKeys api,
AbstractRequest request) {
long now = time.milliseconds();
RequestFutureCompletionHandler future = new RequestFutureCompletionHandler(); // 回调函数
RequestHeader header = client.nextRequestHeader(api);
RequestSend send = new RequestSend(node.idString(), header, request.toStruct());
put(node, new ClientRequest(now, true, send, future)); // request方法哦unsent中
return future; // 并返回回调函数类的引用
}

在调用ConsumerNetworkClient#send(..)后又紧接着调用了Future#compose(..)。如下:

private RequestFuture<Void> sendGroupCoordinatorRequest() {
Node node = this.client.leastLoadedNode();
if (node == null) {
return RequestFuture.noBrokersAvailable();
} else {
log.debug("Sending coordinator request for group {} to broker {}", groupId, node);
GroupCoordinatorRequest metadataRequest = new GroupCoordinatorRequest(this.groupId);
return client.send(node, ApiKeys.GROUP_COORDINATOR, metadataRequest) // send后返回FutureRequest,然后又调用compose方法
.compose(new RequestFutureAdapter<ClientResponse, Void>() {
@Override
public void onSuccess(ClientResponse response, RequestFuture<Void> future) {
handleGroupMetadataResponse(response, future);
}
});
}
}

Future#compose(..)方法又两个作用

  1. 添加FutureRequest的listeners
  2. 返回一个新的FutureRequest,用新FutureRequest来判断状态
public <S> RequestFuture<S> compose(final RequestFutureAdapter<T, S> adapter) {
final RequestFuture<S> adapted = new RequestFuture<S>(); // 返回新的RequestFuture
addListener(new RequestFutureListener<T>() { // 添加到原先FutureRequest中的listeners中
@Override
public void onSuccess(T value) {
adapter.onSuccess(value, adapted); // 返回response后会调用listeners,从而会设置新的RequestFuture状态,我们就可以根据这个新的RequestFuture来判断response处理状态。
} @Override
public void onFailure(RuntimeException e) {
adapter.onFailure(e, adapted);
}
});
return adapted;
}

所以将ClientRequest放到map中后,最终我们持有的是compose中新建的FutureRequest,如AbstractCoordinator#ensureCoordinatorReady(..):

public void ensureCoordinatorReady() {
while (coordinatorUnknown()) {
RequestFuture<Void> future = sendGroupCoordinatorRequest();// 最终返回compose返回的future。
client.poll(future); // 在poll中不停的轮训future的状态 if (future.failed()) {
if (future.isRetriable())
client.awaitMetadataUpdate();
else
throw future.exception();
} else if (coordinator != null && client.connectionFailed(coordinator)) {
coordinatorDead();
time.sleep(retryBackoffMs);
} }
} public void poll(RequestFuture<?> future) {
while (!future.isDone()) // 轮训future状态,当response做相应处理会调用回调函数,从而设置future相应状态。
poll(Long.MAX_VALUE);
}

总结

kafka客户端中使用了大量的回调函数做请求的处理,理解回调函数很重要,附回调函数链接:

http://www.cnblogs.com/set-cookie/p/8996951.html

kafka中的回调函数的更多相关文章

  1. PHP中的回调函数和匿名函数

    html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,bi ...

  2. 理解和使用 JavaScript 中的回调函数

    理解和使用 JavaScript 中的回调函数 标签: 回调函数指针js 2014-11-25 01:20 11506人阅读 评论(4) 收藏 举报  分类: JavaScript(4)    目录( ...

  3. js中的回调函数的理解和使用方法

    js中的回调函数的理解和使用方法 一. 回调函数的作用 js代码会至上而下一条线执行下去,但是有时候我们需要等到一个操作结束之后再进行下一个操作,这时候就需要用到回调函数. 二. 回调函数的解释 因为 ...

  4. [转]理解与使用Javascript中的回调函数

    在Javascript中,函数是第一类对象,这意味着函数可以像对象一样按照第一类管理被使用.既然函数实际上是对象:它们能被“存储”在变量中,能作为函数参数被传递,能在函数中被创建,能从函数中返回. 因 ...

  5. 【JavaScript】理解与使用Javascript中的回调函数

    在Javascript中,函数是第一类对象,这意味着函数可以像对象一样按照第一类管理被使用.既然函数实际上是对象:它们能被“存储”在变量中,能作为函数参数被传递,能在函数中被创建,能从函数中返回. 因 ...

  6. C中的回调函数

    C语言中应用回调函数的地方非常多,如Nginx中: struct ngx_command_s { ngx_str_t name; ngx_uint_t type; char *(*set)(ngx_c ...

  7. Java中的回调函数学习

    Java中的回调函数学习 博客分类: J2SE JavaJ#  一般来说分为以下几步: 声明回调函数的统一接口interface A,包含方法callback(); 在调用类caller内将该接口设置 ...

  8. 转: jquery中ajax回调函数使用this

    原文地址:jquery中ajax回调函数使用this 写ajax请求的时候success中代码老是不能正常执行,找了半天原因.代码如下 $.ajax({type: 'GET', url: " ...

  9. 理解javascript中的回调函数(callback)【转】

    在JavaScrip中,function是内置的类对象,也就是说它是一种类型的对象,可以和其它String.Array.Number.Object类的对象一样用于内置对象的管理.因为function实 ...

随机推荐

  1. DH密钥交换协议

    密钥交换 密钥交换简单点来说就是允许两名用户在公开媒体上交换信息以生成"一致"的.可以共享的密钥.也就是由甲方产出一对密钥(公钥.私钥),乙方依照甲方公钥产生乙方密钥对(公钥.私钥 ...

  2. NSSCTF-原来你也玩原神

    是一个杂项的题目,看到题目名字的时候,以为是和之前遇到的一个杂项题里面的原神的编码有关,然后发现不是的,给的是一个压缩包文件,使用winhex打开,并没有看到压缩包的文件头也没有看到,使用一般常用的b ...

  3. 使用helm安装nfs-subdir-external-provisioner实现动态创建存储

    存储组件 nfs-subdir-external-provisioner 是一个存储资源自动调配器,它可用将现有的 NFS 服务器通过持久卷声明来支持 Kubernetes 持久卷的动态分配.此组件是 ...

  4. MySQL 学习笔记(一)MySQL 事务的ACID特性

    MySQL事务是什么,它就是一组数据库的操作,是访问数据库的程序单元,事务中可能包含一个或者多个 SQL 语句.这些SQL 语句要么都执行.要么都不执行.我们知道,在MySQL 中,有不同的存储引擎, ...

  5. Pycharm:调试、断点

    1.调试:Shift+F10 或 2.快捷键: 步进:F8 进入函数内:F7 运行到下一个断点处:F9 3.删除所有断点 菜单栏->Run->View BreakPoints.. 减号代表 ...

  6. 在矩池云上复现 PaddleGAN 照片转油画风格教程

    我选用的是cuda10.1纯镜像 案例来自paddlepaddle官方PaddleGAN库中,可以查看 https://github.com/PaddlePaddle/PaddleGAN/ https ...

  7. MySQL-DB-封装-升级版

    <?php class DB { //定义属性 private $host;//主机名 private $port;//端口号 private $name;//用户名 private $pass ...

  8. html2canvas滚动截图

    滚动截图 项目需求要进行动态的滚动截图搜索一下发现html2canvas可以实现截图,但是滚动截图网上搜罗了一遍发现不是很完善所以记录下 首先npm一下安装依赖: npm install html2c ...

  9. 理解并手写 call() 函数

    手写自己的call,我们要先通过call的使用,了解都需要完成些什么功能? call()进行了调用,是个方法,已知是建立在原型上的,使用了多个参数(绑定的对象+传递的参数). 我们把手写的函数起名为m ...

  10. netty通信

    学习netty之前,要先了解操作系统中的IO.零拷贝(已经附上链接了) 一.netty的简单介绍 Netty 是由 JBOSS 提供的一个 Java 开源框架,现为 Github 上的独立项目. Ne ...