簡體   English   中英

如何使 Kafka 代理故障轉移對消費者起作用?

[英]How to make Kafka broker failover to work regarding consumers?

使復制代理針對消費者工作似乎非常復雜:似乎當停止某些代理時,一些消費者不再工作,而當特定代理再次啟動時,那些沒有工作的消費者會收到所有“丟失”的信息消息。

我正在使用 2 個經紀人方案。 創建了一個像這樣的復制主題:

  $KAFKA_HOME/bin/kafka-topics.sh --create \
  --zookeeper localhost:2181 \
  --replication-factor 2 \
  --partitions 3 \
  --topic replicated_topic

服務器配置的摘錄如下所示(請注意,除了端口、代理 ID 和日志目錄外,兩台服務器都相同):

# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# see kafka.server.KafkaConfig for additional details and defaults

############################# Server Basics #############################

# The id of the broker. This must be set to a unique integer for each broker.
broker.id=0
############################# Socket Server Settings #############################

# The address the socket server listens on. It will get the value returned from 
# java.net.InetAddress.getCanonicalHostName() if not configured.
#   FORMAT:
#     listeners = listener_name://host_name:port
#   EXAMPLE:
#     listeners = PLAINTEXT://your.host.name:9092
listeners=PLAINTEXT://:9092

# Hostname and port the broker will advertise to producers and consumers. If not set, 
# it uses the value for "listeners" if configured.  Otherwise, it will use the value
# returned from java.net.InetAddress.getCanonicalHostName().
#advertised.listeners=PLAINTEXT://your.host.name:9092

# Maps listener names to security protocols, the default is for them to be the same. See the config documentation for more details
#listener.security.protocol.map=PLAINTEXT:PLAINTEXT,SSL:SSL,SASL_PLAINTEXT:SASL_PLAINTEXT,SASL_SSL:SASL_SSL

# The number of threads that the server uses for receiving requests from the network and sending responses to the network
num.network.threads=3

# The number of threads that the server uses for processing requests, which may include disk I/O
num.io.threads=8

# The send buffer (SO_SNDBUF) used by the socket server
socket.send.buffer.bytes=102400

# The receive buffer (SO_RCVBUF) used by the socket server
socket.receive.buffer.bytes=102400

# The maximum size of a request that the socket server will accept (protection against OOM)
socket.request.max.bytes=104857600


############################# Log Basics #############################

# A comma seperated list of directories under which to store log files
log.dirs=/tmp/kafka-logs0

# The default number of log partitions per topic. More partitions allow greater
# parallelism for consumption, but this will also result in more files across
# the brokers.
num.partitions=1

# The number of threads per data directory to be used for log recovery at startup and flushing at shutdown.
# This value is recommended to be increased for installations with data dirs located in RAID array.
num.recovery.threads.per.data.dir=1

############################# Internal Topic Settings  #############################
# The replication factor for the group metadata internal topics "__consumer_offsets" and "__transaction_state"
# For anything other than development testing, a value greater than 1 is recommended for to ensure availability such as 3.
offsets.topic.replication.factor=2
transaction.state.log.replication.factor=1
transaction.state.log.min.isr=1

############################# Log Flush Policy #############################

# Messages are immediately written to the filesystem but by default we only fsync() to sync
# the OS cache lazily. The following configurations control the flush of data to disk.
# There are a few important trade-offs here:
#    1. Durability: Unflushed data may be lost if you are not using replication.
#    2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush.
#    3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks.
# The settings below allow one to configure the flush policy to flush data after a period of time or
# every N messages (or both). This can be done globally and overridden on a per-topic basis.

# The number of messages to accept before forcing a flush of data to disk
#log.flush.interval.messages=10000

# The maximum amount of time a message can sit in a log before we force a flush
#log.flush.interval.ms=1000

############################# Log Retention Policy #############################

# The following configurations control the disposal of log segments. The policy can
# be set to delete segments after a period of time, or after a given size has accumulated.
# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens
# from the end of the log.

# The minimum age of a log file to be eligible for deletion due to age
log.retention.hours=168

# A size-based retention policy for logs. Segments are pruned from the log unless the remaining
# segments drop below log.retention.bytes. Functions independently of log.retention.hours.
#log.retention.bytes=1073741824

# The maximum size of a log segment file. When this size is reached a new log segment will be created.
log.segment.bytes=1073741824

# The interval at which log segments are checked to see if they can be deleted according
# to the retention policies
log.retention.check.interval.ms=300000

############################# Zookeeper #############################

# Zookeeper connection string (see zookeeper docs for details).
# This is a comma separated host:port pairs, each corresponding to a zk
# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002".
# You can also append an optional chroot string to the urls to specify the
# root directory for all kafka znodes.
zookeeper.connect=localhost:2181

# Timeout in ms for connecting to zookeeper
zookeeper.connection.timeout.ms=6000


############################# Group Coordinator Settings #############################

# The following configuration specifies the time, in milliseconds, that the GroupCoordinator will delay the initial consumer rebalance.
# The rebalance will be further delayed by the value of group.initial.rebalance.delay.ms as new members join the group, up to a maximum of max.poll.interval.ms.
# The default value for this is 3 seconds.
# We override this to 0 here as it makes for a better out-of-the-box experience for development and testing.
# However, in production environments the default value of 3 seconds is more suitable as this will help to avoid unnecessary, and potentially expensive, rebalances during application startup.
group.initial.rebalance.delay.ms=0

讓我們使用 2 個經紀人來描述我的主題:

Topic:replicated_topic  PartitionCount:3    ReplicationFactor:2 Configs:
    Topic: replicated_topic Partition: 0    Leader: 1   Replicas: 1,0   Isr: 1,0
    Topic: replicated_topic Partition: 1    Leader: 0   Replicas: 0,1   Isr: 1,0
    Topic: replicated_topic Partition: 2    Leader: 1   Replicas: 1,0   Isr: 1,0

我們看一下消費者的代碼: Consumer ( impl Callable )

@Override
public Void call() throws Exception {
    final Properties props = new Properties();
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
            bootstrapServers);
    props.put(ConsumerConfig.GROUP_ID_CONFIG,
            groupId);
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
            IntegerDeserializer.class.getName());
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
            StringDeserializer.class.getName());

    final Consumer<Integer, String> consumer = new KafkaConsumer<>(props);

    consumer.subscribe(Collections.singletonList(topicName));

    ConsumerRecords<Integer, String> records = null;
    while (!Thread.currentThread().isInterrupted()) {
        records = consumer.poll(1000);
        if (records.isEmpty()) {
            continue;
        }
        records.forEach(rec -> LOGGER.debug("{}@{} consumed from topic {}, partition {} pair ({},{})",
                ConsumerCallable.class.getSimpleName(), hashCode(), rec.topic(), rec.partition(), rec.key(), rec.value()));
        consumer.commitAsync();
    }

    consumer.close();
    return null;
}

生產者和主要代碼:

private static final String TOPIC_NAME = "replicated_topic";
private static final String BOOTSTRAP_SERVERS = "localhost:9092, localhost:9093";
private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);

public static void main(String[] args) {

    ExecutorService executor = Executors.newCachedThreadPool();
    executor.submit(new ConsumerCallable(TOPIC_NAME, BOOTSTRAP_SERVERS, "group1"));
    executor.submit(new ConsumerCallable(TOPIC_NAME, BOOTSTRAP_SERVERS, "group2"));
    executor.submit(new ConsumerCallable(TOPIC_NAME, BOOTSTRAP_SERVERS, "group3"));

    try (Producer<Integer, String> producer = createProducer()) {
        Scanner scanner = new Scanner(System.in);
        String line = null;
        LOGGER.debug("Please enter 'k v' on the command line to send to Kafka or 'quit' to exit");
        while (scanner.hasNextLine()) {
            line = scanner.nextLine();
            if (line.trim().toLowerCase().equals("quit")) {
                break;
            }
            String[] elements = line.split(" ");
            Integer key = Integer.parseInt(elements[0]);
            String value = elements[1];
            producer.send(new ProducerRecord<>(TOPIC_NAME, key, value));
            producer.flush();
        }
    }
    executor.shutdownNow();
}

private static Producer<Integer, String> createProducer() {
    Properties props = new Properties();
    props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,
            BOOTSTRAP_SERVERS);
    props.put(ProducerConfig.CLIENT_ID_CONFIG, "KafkaExampleProducer");
    props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
            IntegerSerializer.class.getName());
    props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
            StringSerializer.class.getName());
    return new KafkaProducer<>(props);
}

現在讓我們看看行為:

  1. 所有經紀人都起來了:

kafka 主題的輸出:

Topic:replicated_topic  PartitionCount:3    ReplicationFactor:2 Configs:
    Topic: replicated_topic Partition: 0    Leader: 1   Replicas: 1,0   Isr: 1,0
    Topic: replicated_topic Partition: 1    Leader: 0   Replicas: 0,1   Isr: 1,0
    Topic: replicated_topic Partition: 2    Leader: 1   Replicas: 1,0   Isr: 1,0

程序輸出:

12:52:30.460 DEBUG Main - Please enter 'k v' on the command line to send to Kafka or 'quit' to exit
1 u
12:52:35.555 DEBUG ConsumerCallable - ConsumerCallable@1241910294 consumed from topic replicated_topic, partition 0 pair (1,u)
12:52:35.559 DEBUG ConsumerCallable - ConsumerCallable@1361430455 consumed from topic replicated_topic, partition 0 pair (1,u)
12:52:35.559 DEBUG ConsumerCallable - ConsumerCallable@186743616 consumed from topic replicated_topic, partition 0 pair (1,u)
2 d
12:52:38.096 DEBUG ConsumerCallable - ConsumerCallable@186743616 consumed from topic replicated_topic, partition 2 pair (2,d)
12:52:38.098 DEBUG ConsumerCallable - ConsumerCallable@1361430455 consumed from topic replicated_topic, partition 2 pair (2,d)
12:52:38.100 DEBUG ConsumerCallable - ConsumerCallable@1241910294 consumed from topic replicated_topic, partition 2 pair (2,d)

由於消費者在不同的組中,所有消息都廣播給他們,一切正常。

2 關閉代理 2:

描述主題:

Topic:replicated_topic  PartitionCount:3    ReplicationFactor:2 Configs:
    Topic: replicated_topic Partition: 0    Leader: 0   Replicas: 1,0   Isr: 0
    Topic: replicated_topic Partition: 1    Leader: 0   Replicas: 0,1   Isr: 0
    Topic: replicated_topic Partition: 2    Leader: 0   Replicas: 1,0   Isr: 0

程序輸出:

3 t
12:57:03.898 DEBUG ConsumerCallable - ConsumerCallable@186743616 consumed from topic replicated_topic, partition 1 pair (3,t)
4 p
12:57:06.058 DEBUG ConsumerCallable - ConsumerCallable@186743616 consumed from topic replicated_topic, partition 1 pair (4,p)

現在只有 1 個消費者接收數據。 讓我們再次啟動代理 2:現在其他 2 個消費者收到丟失的數據:

12:57:50.863 DEBUG ConsumerCallable - ConsumerCallable@1241910294 consumed from topic replicated_topic, partition 1 pair (3,t)
12:57:50.863 DEBUG ConsumerCallable - ConsumerCallable@1241910294 consumed from topic replicated_topic, partition 1 pair (4,p)
12:57:50.870 DEBUG ConsumerCallable - ConsumerCallable@1361430455 consumed from topic replicated_topic, partition 1 pair (3,t)
12:57:50.870 DEBUG ConsumerCallable - ConsumerCallable@1361430455 consumed from topic replicated_topic, partition 1 pair (4,p)
  1. 關閉broker 1:

現在只有 2 個消費者接收數據:

5 c
12:59:13.718 DEBUG ConsumerCallable - ConsumerCallable@1361430455 consumed from topic replicated_topic, partition 2 pair (5,c)
12:59:13.737 DEBUG ConsumerCallable - ConsumerCallable@1241910294 consumed from topic replicated_topic, partition 2 pair (5,c)
6 s
12:59:16.437 DEBUG ConsumerCallable - ConsumerCallable@1361430455 consumed from topic replicated_topic, partition 2 pair (6,s)
12:59:16.438 DEBUG ConsumerCallable - ConsumerCallable@1241910294 consumed from topic replicated_topic, partition 2 pair (6,s)

如果我帶上它,其他消費者也會收到丟失的數據。

我的觀點是(對不起,我寫了很多,但我正在嘗試捕捉上下文),如何確保無論我停止哪個代理,消費者都能正常工作? (正常接收所有消息)?

PS:我嘗試設置 offsets.topic.replication.factor=2 或 3,但沒有任何效果。

如果否,將不忽略發送給該代理的消息。 活動代理的數量少於配置的副本。 每當新的Kafka代理加入群集時,數據就會復制到該節點。 https://stackoverflow.com/a/38998062/6274525

因此,當您的代理2發生故障時,消息仍然會被推送到另一個活動的代理,因為存在1個實時代理,並且復制因子為2。由於您的其他2個使用者已訂閱了代理2(發生故障),因此他們無法使用。

當您的代理2再次啟動時,數據將復制到該新節點,因此連接到該節點的使用者將收到該消息(被您稱為“丟失”消息)。

請確保已將名為offsets.topic.replication.factor的屬性更改為至少3。

此屬性用於管理偏移量和使用者交互。 啟動kafka服務器時,它將自動創建名稱為__consumer_offsets的主題。 因此,如果未在此主題中創建副本,那么使用者就無法確定是否將某些內容推送到它正在偵聽的主題中。

鏈接到此屬性的詳細信息: https : //kafka.apache.org/documentation/#brokerconfigs

所以這是我對於3節點Kafka群集和3副本Kafka主題看到的行為

  1. 如果您降低1個非領導者的節點-那么您就很好了,消費者繼續工作

  2. 如果降低領導者節點,那么使用者可能會或可能不會工作(工作=繼續收到發布)

這是一個問題。 我使用的是Kafka 1.1.0。

  1. 此外,如果您殺死了領導者0並觀察到消費者不起作用,您還將注意到新的領導者現在是1(或2)。

  2. 您帶回經紀人“ 0”,並觀察到消費者收到“丟失”消息

  3. 現在放下新的領導者(1 OR 2),消費者仍然可以正常工作。 因此,問題似乎正在扼殺最初的領導者。

會研究更多並返回

因此出現的模式是,如果您殺死啟動群集時啟動的FIRST代理,則使用者將停止接收消息。 將測試更多並更新。 顯然,只要維持法定人數,關閉其他經紀商就不會影響消費者。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM