自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Kafka之消費與心跳

系統(tǒng) Linux Kafka
kafka是一個分布式,分區(qū)的,多副本的,多訂閱者的消息發(fā)布訂閱系統(tǒng)(分布式MQ系統(tǒng)),可以用于搜索日志,監(jiān)控日志,訪問日志等。kafka是一個分布式,分區(qū)的,多副本的,多訂閱者的消息發(fā)布訂閱系統(tǒng)(分布式MQ系統(tǒng)),可以用于搜索日志,監(jiān)控日志,訪問日志等。今天小編來領大家一起來學習一下Kafka消費與心跳機制。

 導讀kafka是一個分布式,分區(qū)的,多副本的,多訂閱者的消息發(fā)布訂閱系統(tǒng)(分布式MQ系統(tǒng)),可以用于搜索日志,監(jiān)控日志,訪問日志等。kafka是一個分布式,分區(qū)的,多副本的,多訂閱者的消息發(fā)布訂閱系統(tǒng)(分布式MQ系統(tǒng)),可以用于搜索日志,監(jiān)控日志,訪問日志等。今天小編來領大家一起來學習一下Kafka消費與心跳機制。

1、Kafka消費

首先,我們來看看消費。Kafka提供了非常簡單的消費API,使用者只需初始化Kafka的Broker Server地址,然后實例化KafkaConsumer類即可拿到Topic中的數(shù)據(jù)。一個簡單的Kafka消費實例代碼如下所示:

  1. public class JConsumerSubscribe extends Thread {  
  2.     public static void main(String[] args) {        JConsumerSubscribe jconsumer = new JConsumerSubscribe();        jconsumer.start();    }    /** 初始化Kafka集群信息. */    private Properties configure() {        Properties props = new Properties();        props.put("bootstrap.servers""dn1:9092,dn2:9092,dn3:9092");// 指定Kafka集群地址  
  3.         props.put("group.id""ke");// 指定消費者組  
  4.         props.put("enable.auto.commit""true");// 開啟自動提交  
  5.         props.put("auto.commit.interval.ms""1000");// 自動提交的時間間隔  
  6.         // 反序列化消息主鍵        props.put("key.deserializer""org.apache.kafka.common.serialization.StringDeserializer");  
  7.         // 反序列化消費記錄        props.put("value.deserializer""org.apache.kafka.common.serialization.StringDeserializer");  
  8.         return props;  
  9.     }    /** 實現(xiàn)一個單線程消費者. */    @Override    public void run() {        // 創(chuàng)建一個消費者實例對象        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(configure());        // 訂閱消費主題集合        consumer.subscribe(Arrays.asList("test_kafka_topic"));  
  10.         // 實時消費標識        boolean flag = true;  
  11.         while (flag) {  
  12.             // 獲取主題消息數(shù)據(jù)            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));  
  13.             for (ConsumerRecord<String, String> record : records)  
  14.                 // 循環(huán)打印消息記錄                System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());  
  15.         }        // 出現(xiàn)異常關(guān)閉消費者對象        consumer.close();  
  16.     }}  

 上述代碼我們就可以非常便捷地拿到Topic中的數(shù)據(jù)。但是,當我們調(diào)用poll方法拉取數(shù)據(jù)的時候,Kafka Broker Server做了那些事情。接下來,我們可以去看看源代碼的實現(xiàn)細節(jié)。核心代碼如下:

org.apache.kafka.clients.consumer.KafkaConsumer

  1. private ConsumerRecords<K, V> poll(final long timeoutMs, final boolean includeMetadataInTimeout) {  
  2.         acquireAndEnsureOpen();        try {  
  3.             if (timeoutMs < 0) throw new IllegalArgumentException("Timeout must not be negative");  
  4.             if (this.subscriptions.hasNoSubscriptionOrUserAssignment()) {  
  5.                 throw new IllegalStateException("Consumer is not subscribed to any topics or assigned any partitions");  
  6.             }            // poll for new data until the timeout expires  
  7.             long elapsedTime = 0L;  
  8.             do {  
  9.                 client.maybeTriggerWakeup();                final long metadataEnd;                if (includeMetadataInTimeout) {  
  10.                     final long metadataStart = time.milliseconds();                    if (!updateAssignmentMetadataIfNeeded(remainingTimeAtLeastZero(timeoutMs, elapsedTime))) {  
  11.                         return ConsumerRecords.empty();  
  12.                     }                    metadataEnd = time.milliseconds();                    elapsedTime += metadataEnd - metadataStart;                } else {  
  13.                     while (!updateAssignmentMetadataIfNeeded(Long.MAX_VALUE)) {  
  14.                         log.warn("Still waiting for metadata");  
  15.                     }                    metadataEnd = time.milliseconds();                }                final Map<TopicPartition, List<ConsumerRecord<K, V>>> records = pollForFetches(remainingTimeAtLeastZero(timeoutMs, elapsedTime));                if (!records.isEmpty()) {  
  16.                     // before returning the fetched records, we can send off the next round of fetches  
  17.                     // and avoid block waiting for their responses to enable pipelining while the user  
  18.                     // is handling the fetched records.  
  19.                     //  
  20.                     // NOTE: since the consumed position has already been updated, we must not allow  
  21.                     // wakeups or any other errors to be triggered prior to returning the fetched records.  
  22.                     if (fetcher.sendFetches() > 0 || client.hasPendingRequests()) {  
  23.                         client.pollNoWakeup();                    }                    return this.interceptors.onConsume(new ConsumerRecords<>(records));  
  24.                 }                final long fetchEnd = time.milliseconds();                elapsedTime += fetchEnd - metadataEnd;            } while (elapsedTime < timeoutMs);  
  25.             return ConsumerRecords.empty();  
  26.         } finally {  
  27.             release();        }    }  

 上述代碼中有個方法pollForFetches,它的實現(xiàn)邏輯如下: 

  1. private Map<TopicPartition, List<ConsumerRecord<K, V>>> pollForFetches(final long timeoutMs) {  
  2.         final long startMs = time.milliseconds();  
  3.         long pollTimeout = Math.min(coordinator.timeToNextPoll(startMs), timeoutMs);  
  4.         // if data is available already, return it immediately  
  5.         final Map<TopicPartition, List<ConsumerRecord<K, V>>> records = fetcher.fetchedRecords();  
  6.         if (!records.isEmpty()) {  
  7.             return records;  
  8.         }  
  9.         // send any new fetches (won't resend pending fetches)  
  10.         fetcher.sendFetches();  
  11.         // We do not want to be stuck blocking in poll if we are missing some positions  
  12.         // since the offset lookup may be backing off after a failure  
  13.         // NOTE: the use of cachedSubscriptionHashAllFetchPositions means we MUST call  
  14.         // updateAssignmentMetadataIfNeeded before this method.  
  15.         if (!cachedSubscriptionHashAllFetchPositions && pollTimeout > retryBackoffMs) {  
  16.             pollTimeout = retryBackoffMs;  
  17.         }  
  18.         client.poll(pollTimeout, startMs, () -> {  
  19.             // since a fetch might be completed by the background thread, we need this poll condition  
  20.             // to ensure that we do not block unnecessarily in poll()  
  21.             return !fetcher.hasCompletedFetches();  
  22.         });  
  23.         // after the long poll, we should check whether the group needs to rebalance  
  24.         // prior to returning data so that the group can stabilize faster  
  25.         if (coordinator.rejoinNeededOrPending()) {  
  26.             return Collections.emptyMap();  
  27.         }  
  28.         return fetcher.fetchedRecords();  
  29.     }  

 上述代碼中加粗的位置,我們可以看出每次消費者客戶端拉取數(shù)據(jù)時,通過poll方法,先調(diào)用fetcher中的fetchedRecords函數(shù),如果獲取不到數(shù)據(jù),就會發(fā)起一個新的sendFetches請求。而在消費數(shù)據(jù)的時候,每個批次從Kafka Broker Server中拉取數(shù)據(jù)是有最大數(shù)據(jù)量限制,默認是500條,由屬性(max.poll.records)控制,可以在客戶端中設置該屬性值來調(diào)整我們消費時每次拉取數(shù)據(jù)的量。

提示:這里需要注意的是,max.poll.records返回的是一個poll請求的數(shù)據(jù)總和,與多少個分區(qū)無關(guān)。因此,每次消費從所有分區(qū)中拉取Topic的數(shù)據(jù)的總條數(shù)不會超過max.poll.records所設置的值。

而在Fetcher的類中,在sendFetches方法中有限制拉取數(shù)據(jù)容量的限制,由屬性(max.partition.fetch.bytes),默認1MB??赡軙羞@樣一個場景,當滿足max.partition.fetch.bytes限制條件,如果需要Fetch出10000條記錄,每次默認500條,那么我們需要執(zhí)行20次才能將這一次通過網(wǎng)絡發(fā)起的請求全部Fetch完畢。

這里,可能有同學有疑問,我們不能將默認的max.poll.records屬性值調(diào)到10000嗎?可以調(diào),但是還有個屬性需要一起配合才可以,這個就是每次poll的超時時間(Duration.ofMillis(100)),這里需要根據(jù)你的實際每條數(shù)據(jù)的容量大小來確定設置超時時間,如果你將最大值調(diào)到10000,當你每條記錄的容量很大時,超時時間還是100ms,那么可能拉取的數(shù)據(jù)少于10000條。

而這里,還有另外一個需要注意的事情,就是會話超時的問題。session.timeout.ms默認是10s,group.min.session.timeout.ms默認是6s,group.max.session.timeout.ms默認是30min。當你在處理消費的業(yè)務邏輯的時候,如果在10s內(nèi)沒有處理完,那么消費者客戶端就會與Kafka Broker Server斷開,消費掉的數(shù)據(jù),產(chǎn)生的offset就沒法提交給Kafka,因為Kafka Broker Server此時認為該消費者程序已經(jīng)斷開,而即使你設置了自動提交屬性,或者設置auto.offset.reset屬性,你消費的時候還是會出現(xiàn)重復消費的情況,這就是因為session.timeout.ms超時的原因?qū)е碌摹?/p>

2、心跳機制

上面在末尾的時候,說到會話超時的情況導致消息重復消費,為什么會有超時?有同學會有這樣的疑問,我的消費者線程明明是啟動的,也沒有退出,為啥消費不到Kafka的消息呢?消費者組也查不到我的ConsumerGroupID呢?這就有可能是超時導致的,而Kafka是通過心跳機制來控制超時,心跳機制對于消費者客戶端來說是無感的,它是一個異步線程,當我們啟動一個消費者實例時,心跳線程就開始工作了。

在org.apache.kafka.clients.consumer.internals.AbstractCoordinator中會啟動一個HeartbeatThread線程來定時發(fā)送心跳和檢測消費者的狀態(tài)。每個消費者都有個org.apache.kafka.clients.consumer.internals.ConsumerCoordinator,而每個ConsumerCoordinator都會啟動一個HeartbeatThread線程來維護心跳,心跳信息存放在org.apache.kafka.clients.consumer.internals.Heartbeat中,聲明的Schema如下所示:

  1. private final int sessionTimeoutMs;  
  2.     private final int heartbeatIntervalMs;  
  3.     private final int maxPollIntervalMs;  
  4.     private final long retryBackoffMs;  
  5.     private volatile long lastHeartbeatSend;   
  6.     private long lastHeartbeatReceive;  
  7.     private long lastSessionReset;  
  8.     private long lastPoll;  
  9.     private boolean heartbeatFailed;  

 心跳線程中的run方法實現(xiàn)代碼如下: 

  1. public void run() {  
  2.             try {  
  3.                 log.debug("Heartbeat thread started");  
  4.                 while (true) {  
  5.                     synchronized (AbstractCoordinator.this) {  
  6.                         if (closed)  
  7.                             return;  
  8.                         if (!enabled) {  
  9.                             AbstractCoordinator.this.wait();  
  10.                             continue;  
  11.                         }                        if (state != MemberState.STABLE) {  
  12.                             // the group is not stable (perhaps because we left the group or because the coordinator  
  13.                             // kicked us out), so disable heartbeats and wait for the main thread to rejoin.  
  14.                             disable();  
  15.                             continue;  
  16.                         }  
  17.                         client.pollNoWakeup();  
  18.                         long now = time.milliseconds();  
  19.                         if (coordinatorUnknown()) {  
  20.                             if (findCoordinatorFuture != null || lookupCoordinator().failed())  
  21.                                 // the immediate future check ensures that we backoff properly in the case that no  
  22.                                 // brokers are available to connect to.  
  23.                                 AbstractCoordinator.this.wait(retryBackoffMs);  
  24.                         } else if (heartbeat.sessionTimeoutExpired(now)) {  
  25.                             // the session timeout has expired without seeing a successful heartbeat, so we should  
  26.                             // probably make sure the coordinator is still healthy.  
  27.                             markCoordinatorUnknown();  
  28.                         } else if (heartbeat.pollTimeoutExpired(now)) {  
  29.                             // the poll timeout has expired, which means that the foreground thread has stalled  
  30.                             // in between calls to poll(), so we explicitly leave the group.  
  31.                             maybeLeaveGroup();  
  32.                         } else if (!heartbeat.shouldHeartbeat(now)) {  
  33.                             // poll again after waiting for the retry backoff in case the heartbeat failed or the  
  34.                             // coordinator disconnected  
  35.                             AbstractCoordinator.this.wait(retryBackoffMs);  
  36.                         } else {  
  37.                             heartbeat.sentHeartbeat(now);  
  38.                             sendHeartbeatRequest().addListener(new RequestFutureListener() {  
  39.                                 @Override  
  40.                                 public void onSuccess(Void value) {  
  41.                                     synchronized (AbstractCoordinator.this) {  
  42.                                         heartbeat.receiveHeartbeat(time.milliseconds());  
  43.                                     }  
  44.                                 }  
  45.                                 @Override  
  46.                                 public void onFailure(RuntimeException e) {  
  47.                                     synchronized (AbstractCoordinator.this) {  
  48.                                         if (e instanceof RebalanceInProgressException) {  
  49.                                             // it is valid to continue heartbeating while the group is rebalancing. This  
  50.                                             // ensures that the coordinator keeps the member in the group for as long  
  51.                                             // as the duration of the rebalance timeout. If we stop sending heartbeats,  
  52.                                             // however, then the session timeout may expire before we can rejoin.  
  53.                                             heartbeat.receiveHeartbeat(time.milliseconds());  
  54.                                         } else {  
  55.                                             heartbeat.failHeartbeat();  
  56.                                             // wake up the thread if it's sleeping to reschedule the heartbeat  
  57.                                             AbstractCoordinator.this.notify();  
  58.                                         }  
  59.                                     }  
  60.                                 }  
  61.                             });  
  62.                         }  
  63.                     }  
  64.                 }  
  65.             } catch (AuthenticationException e) {  
  66.                 log.error("An authentication error occurred in the heartbeat thread", e);  
  67.                 this.failed.set(e);  
  68.             } catch (GroupAuthorizationException e) {  
  69.                 log.error("A group authorization error occurred in the heartbeat thread", e);  
  70.                 this.failed.set(e);  
  71.             } catch (InterruptedException | InterruptException e) {  
  72.                 Thread.interrupted();  
  73.                 log.error("Unexpected interrupt received in heartbeat thread", e);  
  74.                 this.failed.set(new RuntimeException(e));  
  75.             } catch (Throwable e) {  
  76.                 log.error("Heartbeat thread failed due to unexpected error", e);  
  77.                 if (e instanceof RuntimeException)  
  78.                     this.failed.set((RuntimeException) e);  
  79.                 else  
  80.                     this.failed.set(new RuntimeException(e));  
  81.             } finally {  
  82.                 log.debug("Heartbeat thread has closed");  
  83.             }  
  84.         }  

 在心跳線程中這里面包含兩個最重要的超時函數(shù),它們是sessionTimeoutExpired和pollTimeoutExpired。 

  1. public boolean sessionTimeoutExpired(long now) {  
  2.         return now - Math.max(lastSessionReset, lastHeartbeatReceive) > sessionTimeoutMs;  
  3. }public boolean pollTimeoutExpired(long now) {  
  4.         return now - lastPoll > maxPollIntervalMs;  
  5. }  

 2.1、sessionTimeoutExpired

如果是sessionTimeout超時,則會被標記為當前協(xié)調(diào)器處理斷開,此時,會將消費者移除,重新分配分區(qū)和消費者的對應關(guān)系。在Kafka Broker Server中,Consumer Group定義了5種(如果算上Unknown,應該是6種狀態(tài))狀態(tài),org.apache.kafka.common.ConsumerGroupState,如下圖所示:


2.2、pollTimeoutExpired

如果觸發(fā)了poll超時,此時消費者客戶端會退出ConsumerGroup,當再次poll的時候,會重新加入到ConsumerGroup,觸發(fā)RebalanceGroup。而KafkaConsumer Client是不會幫我們重復poll的,需要我們自己在實現(xiàn)的消費邏輯中不停地調(diào)用poll方法。

3.分區(qū)與消費線程

關(guān)于消費分區(qū)與消費線程的對應關(guān)系,理論上消費線程數(shù)應該小于等于分區(qū)數(shù)。之前是有這樣一種觀點,一個消費線程對應一個分區(qū),當消費線程等于分區(qū)數(shù)是最大化線程的利用率。直接使用KafkaConsumer Client實例,這樣使用確實沒有什么問題。但是,如果我們有富裕的CPU,其實還可以使用大于分區(qū)數(shù)的線程,來提升消費能力,這就需要我們對KafkaConsumer Client實例進行改造,實現(xiàn)消費策略預計算,利用額外的CPU開啟更多的線程,來實現(xiàn)消費任務分片。Linux就該這么學

 

責任編輯:姜華 來源: 今日頭條
相關(guān)推薦

2020-09-30 14:07:05

Kafka心跳機制API

2022-07-07 09:00:49

RocketMQ消費者消息消費

2022-03-07 10:15:28

KafkaZookeeper存儲

2023-06-01 08:08:38

kafka消費者分區(qū)策略

2019-09-23 08:27:15

TCP長連接心跳

2013-08-22 09:36:52

移動終端安全移動安全移動策略

2024-03-20 08:33:00

Kafka線程安全Rebalance

2021-12-27 08:22:18

Kafka消費模型

2024-09-23 20:55:04

2023-11-27 17:29:43

Kafka全局順序性

2019-12-16 09:37:19

Kafka架構(gòu)數(shù)據(jù)

2024-08-23 16:04:45

2021-12-28 12:01:59

Kafka 消費者機制

2021-07-08 05:52:34

Kafka架構(gòu)主從架構(gòu)

2024-10-31 11:49:41

Kafka管理死信隊列

2021-10-11 07:01:33

混合云多云數(shù)據(jù)

2019-12-03 11:00:08

spring bootspring-kafkJava

2024-07-05 11:01:13

2023-12-11 07:12:21

心跳檢測重連機制服務端

2020-12-04 10:31:56

組消費分區(qū)Kafka
點贊
收藏

51CTO技術(shù)棧公眾號