kafka中的回调函数
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(..)方法又两个作用
- 添加FutureRequest的listeners
- 返回一个新的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中的回调函数的更多相关文章
- PHP中的回调函数和匿名函数
html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,bi ...
- 理解和使用 JavaScript 中的回调函数
理解和使用 JavaScript 中的回调函数 标签: 回调函数指针js 2014-11-25 01:20 11506人阅读 评论(4) 收藏 举报 分类: JavaScript(4) 目录( ...
- js中的回调函数的理解和使用方法
js中的回调函数的理解和使用方法 一. 回调函数的作用 js代码会至上而下一条线执行下去,但是有时候我们需要等到一个操作结束之后再进行下一个操作,这时候就需要用到回调函数. 二. 回调函数的解释 因为 ...
- [转]理解与使用Javascript中的回调函数
在Javascript中,函数是第一类对象,这意味着函数可以像对象一样按照第一类管理被使用.既然函数实际上是对象:它们能被“存储”在变量中,能作为函数参数被传递,能在函数中被创建,能从函数中返回. 因 ...
- 【JavaScript】理解与使用Javascript中的回调函数
在Javascript中,函数是第一类对象,这意味着函数可以像对象一样按照第一类管理被使用.既然函数实际上是对象:它们能被“存储”在变量中,能作为函数参数被传递,能在函数中被创建,能从函数中返回. 因 ...
- C中的回调函数
C语言中应用回调函数的地方非常多,如Nginx中: struct ngx_command_s { ngx_str_t name; ngx_uint_t type; char *(*set)(ngx_c ...
- Java中的回调函数学习
Java中的回调函数学习 博客分类: J2SE JavaJ# 一般来说分为以下几步: 声明回调函数的统一接口interface A,包含方法callback(); 在调用类caller内将该接口设置 ...
- 转: jquery中ajax回调函数使用this
原文地址:jquery中ajax回调函数使用this 写ajax请求的时候success中代码老是不能正常执行,找了半天原因.代码如下 $.ajax({type: 'GET', url: " ...
- 理解javascript中的回调函数(callback)【转】
在JavaScrip中,function是内置的类对象,也就是说它是一种类型的对象,可以和其它String.Array.Number.Object类的对象一样用于内置对象的管理.因为function实 ...
随机推荐
- 网络测试技术——802.1X原理
一.以太网优点缺点 1.以太网优点 (1)即插即用,简单快捷 (2)任何一台电脑只要接入网络便有访问网络资源的权限 2.以太网缺点 (1)缺乏安全认证机制(二层) (2)电脑接到交换机上就能访问网络 ...
- RFC2544吞吐量测试详细步骤-信而泰Renix软件操作演示
关键词:RFC1242:RFC2544:吞吐量:吞吐率. 吞吐量概述:吞吐量即吞吐率,这个词首先在RFC1242中被提出,是评估网络设备性能的首要指标,其定义是在设备没有丢帧的情况下的最大的转发速率, ...
- 自助BI工具是BI行业发展的趋势吗?
自助BI和分析通过提供交互式数据可视化,图表,图形,报告和分析,帮助业务用户做出决策.将大量数据导出到电子表格以转换为图表和数据透视表的日子现在已经结束.自助BI工具提供基于浏览器的客户端界面,适用于 ...
- oj教程--贪心
贪心算法(又称贪婪算法)是指,在对问题求解时,总是做出在当前看来是最好的选择.也就是说,不从整体最优上加以考虑,他所做出的是在某种意义上的局部最优解. 贪心算法不是对所有问题都能得到整体最优解,关键是 ...
- 探究Spring原理
探究Spring原理 探究IoC原理 首先我们大致了解一下ApplicationContext的加载流程: 我们可以看到,整个过程极为复杂,一句话肯定是无法解释的,所以我们就从ApplicationC ...
- Python:使用piecewise与curve_fit进行三段拟合
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14, 15,16,17,18,19,20,21], dtype=float) y = ...
- Java:命令行参数的传入和调用
1.传入 传入时机:执行时 格式: //编译 javac Main.java //执行并传入命令行参数 -version java Main -version 此时,参数-version就以Strin ...
- 五、Java控制流程
Java流程控制* 用户交互Scanner.Scanner进阶使用 用户交互Scanner 之前我们学习的基本语法中我们并没有实现程序和人的交互,但是Java给我们提供了这样一个工具类,我们可以获 ...
- Jmeter混合场景压力测试
性能测试设计混合场景,一般有几种方式 分别是:1:每个场景设置一个线程组:2:使用if控制器:3:使用吞吐量控制器. 不同的方式实现机制不一样,个人觉得"使用吞吐量控制器"比较方便 ...
- vue项目在nginx中不能刷新问题
修改nginx配置文件为 server { listen 80; server_name www.vue.com; root html/xxx/dist/; client_max_body_size ...