Kafka 心跳机制 重复消费

kafka 心跳机制

Kafka是通过心跳机制来控制消费超时,心跳机制对于消费者客户端来说是无感的,它是一个异步线程,当我们启动一个消费者实例时,心跳线程就开始工作了。心跳超时会导致消息重复消费

在org.apache.kafka.clients.consumer.internals.AbstractCoordinator中会启动一个HeartbeatThread线程来定时发送心跳和检测消费者的状态。每个消费者都有个org.apache.kafka.clients.consumer.internals.ConsumerCoordinator,而每个ConsumerCoordinator都会启动一个HeartbeatThread线程来维护心跳,心跳信息存放在org.apache.kafka.clients.consumer.internals.Heartbeat中,声明的Schema如下所示:

    private final int sessionTimeoutMs;
    private final int heartbeatIntervalMs;
    private final int maxPollIntervalMs;
    private final long retryBackoffMs;
    private volatile long lastHeartbeatSend; 
    private long lastHeartbeatReceive;
    private long lastSessionReset;
    private long lastPoll;
    private boolean heartbeatFailed;

 心跳线程实现方法

public void run() {
            try {
                log.debug("Heartbeat thread started");
                while (true) {
                    synchronized (AbstractCoordinator.this) {
                        if (closed)
                            return;

                        if (!enabled) {
                            AbstractCoordinator.this.wait();
                            continue;
                        }

                        if (state != MemberState.STABLE) {
                            // the group is not stable (perhaps because we left the group or because the coordinator
                            // kicked us out), so disable heartbeats and wait for the main thread to rejoin.
                            disable();
                            continue;
                        }

                        client.pollNoWakeup();
                        long now = time.milliseconds();

                        if (coordinatorUnknown()) {
                            if (findCoordinatorFuture != null || lookupCoordinator().failed())
                                // the immediate future check ensures that we backoff properly in the case that no
                                // brokers are available to connect to.
                                AbstractCoordinator.this.wait(retryBackoffMs);
                        } else if (heartbeat.sessionTimeoutExpired(now)) {
                            // the session timeout has expired without seeing a successful heartbeat, so we should
                            // probably make sure the coordinator is still healthy.
                            markCoordinatorUnknown();
                        } else if (heartbeat.pollTimeoutExpired(now)) {
                            // the poll timeout has expired, which means that the foreground thread has stalled
                            // in between calls to poll(), so we explicitly leave the group.
                            maybeLeaveGroup();
                        } else if (!heartbeat.shouldHeartbeat(now)) {
                            // poll again after waiting for the retry backoff in case the heartbeat failed or the
                            // coordinator disconnected
                            AbstractCoordinator.this.wait(retryBackoffMs);
                        } else {
                            heartbeat.sentHeartbeat(now);

                            sendHeartbeatRequest().addListener(new RequestFutureListener<Void>() {
                                @Override
                                public void onSuccess(Void value) {
                                    synchronized (AbstractCoordinator.this) {
                                        heartbeat.receiveHeartbeat(time.milliseconds());
                                    }
                                }

                                @Override
                                public void onFailure(RuntimeException e) {
                                    synchronized (AbstractCoordinator.this) {
                                        if (e instanceof RebalanceInProgressException) {
                                            // it is valid to continue heartbeating while the group is rebalancing. This
                                            // ensures that the coordinator keeps the member in the group for as long
                                            // as the duration of the rebalance timeout. If we stop sending heartbeats,
                                            // however, then the session timeout may expire before we can rejoin.
                                            heartbeat.receiveHeartbeat(time.milliseconds());
                                        } else {
                                            heartbeat.failHeartbeat();

                                            // wake up the thread if it's sleeping to reschedule the heartbeat
                                            AbstractCoordinator.this.notify();
                                        }
                                    }
                                }
                            });
                        }
                    }
                }
            } catch (AuthenticationException e) {
                log.error("An authentication error occurred in the heartbeat thread", e);
                this.failed.set(e);
            } catch (GroupAuthorizationException e) {
                log.error("A group authorization error occurred in the heartbeat thread", e);
                this.failed.set(e);
            } catch (InterruptedException | InterruptException e) {
                Thread.interrupted();
                log.error("Unexpected interrupt received in heartbeat thread", e);
                this.failed.set(new RuntimeException(e));
            } catch (Throwable e) {
                log.error("Heartbeat thread failed due to unexpected error", e);
                if (e instanceof RuntimeException)
                    this.failed.set((RuntimeException) e);
                else
                    this.failed.set(new RuntimeException(e));
            } finally {
                log.debug("Heartbeat thread has closed");
            }
        }

在心跳线程中这里面包含两个最重要的超时函数,分别是sessionTimeoutExpired() 和 pollTimeoutExpired()。

 

public boolean sessionTimeoutExpired(long now) {
        return now - Math.max(lastSessionReset, lastHeartbeatReceive) > sessionTimeoutMs;
}

public boolean pollTimeoutExpired(long now) {
        return now - lastPoll > maxPollIntervalMs;}

 

  • sessionTimeoutExpired

如果sessionTimeout超时,则会被标记为当前协调器处理断开, 即将将消费者移除,重新分配分区和消费者的对应关系。在Kafka Broker Server中,Consumer Group定义了5中(如果算上Unknown,应该是6种状态)状态,org.apache.kafka.common.ConsumerGroupState,如下图所示:

  • pollTimeoutExpired

如果触发了poll超时,此时消费者客户端会退出ConsumerGroup,当再次poll的时候,会重新加入到ConsumerGroup,触发消费者再平衡策略 RebalanceGroup。而KafkaConsumer Client是不会帮我们重复poll的,需要我们自己在实现的消费逻辑中不停的调用poll方法

 

Kafka消费者负载均衡策略 消费者再平衡 consumer rebalance

Kafka 如何解决消息重复

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 为了防止 Kafka 消息重复消费,可以采取以下几种方法: 1. 使用消费者组:Kafka 允许多个消费者以同一个消费者组的形式订阅同一个主题。当消息被发送到主题时,同一个消费者组中的消费者只会有一个消费者能够接收到消息。这就保证了每个消息只会被消费一次。如果需要进行消息重试,则需要使用不同的消费者组。 2. 使用消息偏移量(offset):Kafka 中每个分区都有一个唯一的偏移量,用于表示分区中已经被消费的消息的位置。消费者可以记录下自己消费到的最后一个偏移量,并在下次启动时从该偏移量处开始消费。这种方式可以避免重复消费,但是需要注意,如果消费者处理消息失败,可能会导致消息被跳过而未被处理。 3. 使用幂等性生产者:幂等性生产者可以确保每个消息只会被发送一次,即使出现了网络故障或者其他异常情况。这样可以避免重复发送消息,从而避免重复消费。 4. 使用去重表:消费者可以使用一个去重表来记录已经消费过的消息,每次消费消息时先查询去重表,如果消息已经存在,则可以跳过该消息。这种方式可以避免重复消费,但是需要注意,去重表需要占用一定的内存空间,并且需要考虑去重表的并发访问问题。 ### 回答2: kafka是一种高吞吐量的分布式消息系统,但在实际应用中,消息重复消费是一个常见的问题。为了解决这个问题,kafka提供了以下几种机制来防止消息重复消费: 1. 分区复制:kafka将消息分发到多个分区,并且可以将每个分区的副本分布在不同的Broker上。当消费者进行消费时,只有一个消费者可以消费同一个分区的消息,其他消费者无法消费相同的消息。这样可以保证消息在同一个分区内不会被重复消费。 2. 消费者组:kafka允许多个消费者组同时消费同一个主题的消息。每当一个新的消费者组加入时,kafka会为该消费者组分配一个独立的消费者实例。不同消费者组之间独立消费,可以避免重复消费。 3. 消息偏移量:kafka使用消息偏移量(offset)来标识消息在分区中的位置。消费者通过管理偏移量来确定下一个要消费的消息。消费者在消费完一个消息后,会将偏移量提交给kafkakafka会保存最新的偏移量。当消费者再次启动后,会从上一次提交的偏移量开始消费,从而避免重复消费。 4. 消费者日志:kafka提供了一个特殊的主题__consumer_offsets,用于保存消费者的偏移量信息。每个消费者组的偏移量会被写入这个主题,当消费者启动时,会从这个主题读取之前提交的偏移量,以便从之前的位置继续消费。 综上所述,kafka通过使用分区复制、消费者组、消息偏移量和消费者日志等机制,有效地防止消息的重复消费。这些机制结合起来,保证了消息的可靠性和一致性,使得kafka成为一个可靠的分布式消息系统。 ### 回答3: Kafka通过以下几种机制来防止消息重复消费: 1. 分区偏移量(Partition Offset):每个消费者在消费消息时会维护一个分区偏移量,用来标识已经消费的消息的位置。消费者可以定期提交其消费的偏移量到Kafka集群,以便记录消费的进度。当消费者重新启动后,可以从上一次提交的偏移量位置继续消费,避免对同一条消息进行重复消费。 2. 消费者组(Consumer Group):在Kafka中,多个消费者可以组成一个消费者组,每个分区只能被同一个消费者组中的一个消费消费。这样可以保证一个消息只会被同一个消费者组中的一个消费消费一次,避免了重复消费的问题。 3. 提交消费偏移量(Commit Offset):消费者在消费消息后,可以手动或自动将消费的偏移量提交给Kafka集群。当消费者发生故障或重新启动时,可以通过已提交的偏移量来恢复消费进度,继续消费消费的消息。 4. 消息的幂等性(Message Idempotence):生产者可以设置消息的幂等性,确保同一消息可以被多次发送但只被消费一次。Kafka通过消息的唯一标识来判断是否是重复消息,如果一个生产者发送了多条相同消息,只有第一条消息会被写入Kafka并被消费,后续相同的消息会被认为是重复消息而被忽略。 通过以上机制Kafka可以有效地防止消息重复消费消费者可以通过维护分区偏移量和消费者组的方式来保证消息只被消费一次,同时可以通过提交消费偏移量和使用幂等性消息来防止重复消费的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值