对于0.10.1以上版本的kafka, 如何从外部重置一个运行中的consumer group的进度呢?比如有一个控制台,可以主动重置任意消费组的消费进度重置到12小时之前, 而用户的程序可以保持运行状态,无需下线或重启。

需要这么几个步骤:

1. 加入这个group

2. 踢掉所有其它group memeber

3. try assign all TopicPartition to this client

4. commit offsets

5. leave group

其中第二步是为了让自己当上leader,当然有可能不需要踢掉其它所有成员就能当上leader(因为谁能当leader实际上是按hashmap的迭代次序来的)。

当上consumer group的leader以后,需要把所有partition assign给自己,这个需要一个特殊的PartitionAssignor。由于这个assignor的协议跟其它consumer group协议不同(但是也可以搞一个表面上协议相同,实际上逻辑不同的assignor),而cooridnator会阻止与当前leader使用的协议不同的成员加入,所以还是需要踢掉其它成员。

public class ExclusiveAssignor extends AbstractPartitionAssignor {

    public interface Callback {
void onSuccess();
} private static Logger LOGGER = LoggerFactory.getLogger(ExclusiveAssignor.class); public static String NAME = "exclusive"; private String leaderId = null;
private Callback callback = null; public void setLeaderId(String leaderId) {
this.leaderId = leaderId;
}
public void setCallBack(Callback callBack){this.callback = callBack;} @Override
public String name() {
return NAME;
} private Map<String, List<String>> consumersPerTopic(Map<String, List<String>> consumerMetadata) {
Map<String, List<String>> res = new HashMap<>();
for (Map.Entry<String, List<String>> subscriptionEntry : consumerMetadata.entrySet()) {
String consumerId = subscriptionEntry.getKey();
for (String topic : subscriptionEntry.getValue())
put(res, topic, consumerId);
}
return res;
} @Override
public Map<String, List<TopicPartition>> assign(Map<String, Integer> partitionsPerTopic,
Map<String, List<String>> subscriptions) {
LOGGER.info("perform exclusive assign");
if(leaderId == null)
throw new IllegalArgumentException("leaderId should already been set before assign is called");
if(callback == null)
throw new IllegalArgumentException("callback should already been set before assign is called"); List<TopicPartition> allPartitions = new ArrayList<TopicPartition>();
partitionsPerTopic.forEach((topic, partitionNumber) -> {
for(int i=0; i < partitionNumber; i++)
allPartitions.add(new TopicPartition(topic, i));
});
Map<String, List<TopicPartition>> assignment = new HashMap<>();
for (String memberId : subscriptions.keySet()) {
assignment.put(memberId, new ArrayList<TopicPartition>());
if(memberId.equals(leaderId)){
assignment.get(memberId).addAll(allPartitions);
}
}
callback.onSuccess();
return assignment;
} }

这个assignor需要知道leaderId是哪个,而leaderId可以在KafkaConsumer的

 protected Map<String, ByteBuffer> performAssignment(String leaderId,
String assignmentStrategy,
Map<String, ByteBuffer> allSubscriptions)

中获取,所以还需要修改一下KafkaConsumer的代码,以确保这个KafkaConsumer的poll并不实际拉取消息,而只是执行commit。

驱逐其它member,可以使用AdminClient完成

  def forceLeave(coordinator: Node, memberId: String, groupId: String) = {
logger.info(s"forcing group member: $memberId to leave group: $groupId ")
send(coordinator, ApiKeys.LEAVE_GROUP, new LeaveGroupRequest(groupId, memberId))
}

最终的逻辑就是

  private def forceCommit(consumer: SimpleKafkaConsumer[_, _], groupId: String, topics: Seq[String], maxRetries: Int, toCommit: Map[TopicPartition, OffsetAndMetadata], coordinatorOpt: Option[Node] = None) = {
consumer.subscribe(JavaConversions.seqAsJavaList(topics))
val assignedAll = new AtomicBoolean(false)
consumer.setExclusiveAssignorCallback(new Callback {
override def onSuccess(): Unit = assignedAll.set(true)
})
var currentRetries = 0
val coordinatorNode = coordinatorOpt.getOrElse(adminClient.findCoordinator(groupId))
while (!assignedAll.get() && currentRetries < maxRetries) {
logger.info(s"trying to reset offset for $groupId, retry count $currentRetries ....")
clearCurrentMembers(coordinatorNode, groupId, Some(ConsumerGroupManager.magicConsumerId))
consumer.poll(5000)
printCurrentAssignment(consumer)
currentRetries = currentRetries + 1
}
if (currentRetries >= maxRetries)
throw new RuntimeException(s"retry exhausted when getting leadership of $groupId")
val javaOffsetToCommit = JavaConversions.mapAsJavaMap(toCommit)
consumer.commitSync(javaOffsetToCommit)
logger.info(s"successfully committed offset for $groupId: $toCommit")
consumer.unsubscribe()
}
  def forceReset(offsetLookupActor: ActorRef, groupId: String, ts: Long, maxRetries: Int)(implicit executionContext: ExecutionContext): Boolean = {
logger.info(s"resetting offset for $groupId to $ts")
val groupSummary = adminClient.describeConsumerGroup(groupId)
val topics = groupSummary.subscribedTopics
if (topics.isEmpty)
throw new IllegalStateException(s"group $groupId currently subscribed no topic")
val offsetToCommit = getOffsetsBehindTs(offsetLookupActor, topics, ts, 10000)
val consumer = createConsumer(groupId)
try {
forceCommit(consumer, groupId, topics, maxRetries, offsetToCommit)
true
} finally {
consumer.close()
}
}

具体代码见 https://github.com/iBuddha/kafka-simple-ui/blob/master/app/kafka/authorization/manager/utils/ConsumerGroupManager.scala

需要注意的是,发送LeaveGroupRequest可能会使得某些成员到broker的连接断掉,发生这种情况的原因是:当一个consumer发送JoinGroupRequest以后,外部的client再发送一个LeaveGroupRequest把这个consumer踢掉,会使得它个consumer无法收到JoinGroupResponse,从而使得NetworkClient以为连接挂掉。不过client以后会重新连接。而且,在外部client踢掉其它成员并且重新commit offset的过程中,其它consumer不一定有机会加入到group中,因而可能不受这个问题的影响。

从外部重置一个运行中consumer group的消费进度的更多相关文章

  1. 在linux下,查看一个运行中的程序, 占用了多少内存

    1. 在linux下,查看一个运行中的程序, 占用了多少内存, 一般的命令有 (1). ps aux: 其中  VSZ(或VSS)列 表示,程序占用了多少虚拟内存. RSS列 表示, 程序占用了多少物 ...

  2. 在linux下,怎么去查看一个运行中的程序, 到底是占用了多少内存

    1. 在linux下,查看一个运行中的程序, 占用了多少内存, 一般的命令有 (1). ps aux: 其中  VSZ(或VSS)列 表示,程序占用了多少虚拟内存. RSS列 表示, 程序占用了多少物 ...

  3. linux下,一个运行中的程序,究竟占用了多少内存

    linux下,一个运行中的程序,究竟占用了多少内存 1. 在linux下,查看一个运行中的程序, 占用了多少内存, 一般的命令有 (1). ps aux: 其中  VSZ(或VSS)列 表示,程序占用 ...

  4. kafka中consumer group 是什么概念?

    同样是逻辑上的概念,是Kafka实现单播和广播两种消息模型的手段.同一个topic的数据,会广播给不同的group:同一个group中的worker,只有一个worker能拿到这个数据.换句话说,对于 ...

  5. WINDOWS中, 如何查看一个运行中的程序是64位还是32位的

    转自:https://blog.csdn.net/dayday3923/article/details/78597453?locationNum=7&fps=1 方法一: 任务管理器法任务管理 ...

  6. linux暂停一个在运行中的进程【转】

    转自:https://blog.csdn.net/Tim_phper/article/details/53536621 转载于: http://www.cszhi.com/20120328/linux ...

  7. Kafka consumer group位移0ffset重设

    本文阐述如何使用Kafka自带的kafka-consumer-groups.sh脚本随意设置消费者组(consumer group)的位移.需要特别强调的是, 这是0.11.0.0版本提供的新功能且只 ...

  8. Kafka设计解析(十九)Kafka consumer group位移重设

    转载自 huxihx,原文链接 Kafka consumer group位移重设 本文阐述如何使用Kafka自带的kafka-consumer-groups.sh脚本随意设置消费者组(consumer ...

  9. Kafka consumer group位移重设

    本文阐述如何使用Kafka自带的kafka-consumer-groups.sh脚本随意设置消费者组(consumer group)的位移.需要特别强调的是, 这是0.11.0.0版本提供的新功能且只 ...

随机推荐

  1. 【hdoj_1398】SquareCoins(母函数)

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=1398 此题采用母函数的知识求解,套用母函数模板即可: http://blog.csdn.net/ten_s ...

  2. windows网卡命令

    netsh interface ip set address name="本地连接" source=dhcpnetsh interface ip set dns name=&quo ...

  3. [水煮 ASP.NET Web API2 方法论](12-2)管理 OData 路由

    问题 如何控制 OData 路由 解决方案 为了注册路由,可以使用  HttpConfigurationExtension 类中 MapODataServiceRoute 的扩展方法.对于单一路由这样 ...

  4. 【cocos2d-js网络教程篇】cocos2d-js http网络请求

    前言 刚入手cocos2d-js,看到网上的JS的http网络请求,大部分都是错的.原因在于,js-tests里面的网络请求实例没有给出加载完成事件.正确的加载完成事件如下: var xhr = cc ...

  5. 用Python创建XML(转)

    在官方网站没有找到多少有用的知识.结果在Python and XML: An Introduction找到了一篇教程,抽空对照做,然后再总结分享出来.先来一个简单的: from xml.dom.min ...

  6. 洛谷P2556 [AHOI2002] 黑白图像压缩 [模拟]

    题目传送门 黑白图像压缩 题目描述 选修基础生物基因学的时候, 小可可在家里做了一次图像学试验. 她知道:整个图像其实就是若干个图像点(称作像素)的序列,假定序列中像素的个数总是 8 的倍数, 于是每 ...

  7. Bzoj1015/洛谷P1197 [JSOI2008]星球大战(并查集)

    题面 Bzoj 洛谷 题解 考虑离线做法,逆序处理,一个一个星球的加入.用并查集维护一下连通性就好了. 具体来说,先将被消灭的星球储存下来,先将没有被消灭的星球用并查集并在一起,这样做可以路径压缩,然 ...

  8. c++风格

    http://web.archive.org/web/20160430022340/http://google.github.io/styleguide/cppguide.html 主要注意几点: 函 ...

  9. 分解质因数法求最大公约数(javascrip实现)

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...

  10. 【模拟+递归+位运算】POJ1753-Flip Game

    由于数据规模不大,利用爆搜即可.第一次用位运算写的,但是转念一想应该用递归更加快,因为位运算没有剪枝啊(qДq ) [思路] 位运算:时间效率较低(172MS),有些辜负了位运算的初衷.首先将二维数组 ...