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. 从数据源支持、支持方式等角度深入了解Smartbi与Tableau

    对数据分析来讲,数据源支持是基本功.让数据分析工具与数据保持一个通道,建立会话.用数据分析应用服务器与我们需要分析的业务数据进行连接,拿到需要的数据进行分析.Smartbi.Tableau系统给我们提 ...

  2. 自助式bi工具为什么这么受欢迎?

    ​目前比较流行的一种BI形式,当属于自助式BI分析,也就是自助分析平台,即在这个倡导凡事自助的社会中,BI也要以这种形式来呈现.自助式的BI分析相比较于传统的形式,是有很多优点的,我为大家整理了一版. ...

  3. 相等性 比较【ReferenceEquals、静态Equals、==(ceq)、实例eEquals】

    感觉 最近学习学疯了,突然对以前熟悉的东西感到陌生.然后又回头重新挖掘一下 什么是相等性呢?以前一直用== 默认是值相等,从未去考虑,是地址相等还值相等.今天就详细的研究一下. .net 平台提供了4 ...

  4. 哈工大 信息安全实验 XSS跨站脚本攻击原理与实践

    XX大学XX学院 <网络攻击与防御> 实验报告 实验报告撰写要求 实验操作是教学过程中理论联系实际的重要环节,而实验报告的撰写又是知识系统化的吸收和升华过程,因此,实验报告应该体现完整性. ...

  5. omnet++:官方文档翻译总结(五)

    Part 6 - 用IDE将结果可视化 学习翻译自:Visualizing the Results - OMNeT++ Technical Articles ①将输出的数值和向量数据可视化(用tict ...

  6. omnet++:使用教程

    学习自:(6条消息) omnet++ 快速入门 | 计算机网络仿真 | omnet++ 入门教程_叶局长的博客-CSDN博客 1.使用omnet仿真的一般步骤 主要有3步: 使用ned(network ...

  7. 面试官:Redis的共享对象池了解吗?

    我正在面试间里焦急地等待着,突然听到了门外的脚步声,随即门被打开,穿着干净满脸清秀的青年走了进来,一股男士香水的淡香扑面而来. 面试官:"平时在工作中用过Redis吗?" 我:&q ...

  8. JZ-018-二叉树的镜像

    二叉树的镜像 题目描述 操作给定的二叉树,将其变换为源二叉树的镜像. 题目链接: 二叉树的镜像 代码 /** * 标题:二叉树的镜像 * 题目描述 * 操作给定的二叉树,将其变换为源二叉树的镜像. * ...

  9. [k8s] k8s基于csi使用rbd存储

    描述 ceph-csi扩展各种存储类型的卷的管理能力,实现第三方存储ceph的各种操作能力与k8s存储系统的结合.通过 ceph-csi 使用 ceph rbd块设备,它动态地提供rbd以支持 Kub ...

  10. tp 实现定时任务

    这里我是用tp6进行测试的:适合做本地项目 博客参考:: https://www.thinkphp.cn/topic/64455.html 1:composer  安装workman插件 compos ...