Kafka Production consumption model
The producer parameters are set and published:
Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("acks", "all"); props.put("retries", 0); props.put("batch.size", 16384); props.put("linger.ms", 1); props.put("buffer.memory", 33554432); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); Producer<String, String> producer = new KafkaProducer<>(props); for(int i = 0; i < 100; i++) producer.send(new ProducerRecord<String, String>("shuaige", Integer.toString(i), Integer.toString(i))); producer.close();
subscriber parameter settings:
Properties props = new Properties (); Props.put ("Bootstrap.servers", "localhost:9092"); Props.put ("Group.id", "Test"); Props.put ("Enable.auto.commit", "true"); Props.put ("auto.commit.interval.ms", "1000"); Props.put ("Key.deserializer", "Org.apache.kafka.common.serialization.StringDeserializer"); Props.put ("Value.deserializer", "Org.apache.kafka.common.serialization.StringDeserializer"); kafkaconsumer<string, string> consumer = new kafkaconsumer<> (props); Consumer.subscribe (Arrays.aslist ("test2")); while (true) {consumerrecords<string, string> records = Consumer.poll (100); For (consumerrecord<string, string> record:records) System.out.printf ("offset =%d, key =%s, value =%s%n ", Record.offset (), Record.key (), Record.value ()); }
- Offset and the position of the consumer
Kafka holds an offset (offset) for each message in the partition, which is a unique identifier for a message in the partition. Also represents the location of the consumer in the partition. For example, one location is 5 of the consumer (indicating that 0 to 4 messages have been consumed), and the next message that receives the message has an offset of 5. There are actually two consumer-related "location" concepts:
The position of the consumer gives the offset of the next record. It is larger than the maximum offset that the consumer sees in the partition. It grows automatically each time a consumer receives a message in a call to poll (long).
The "committed" location is the last offset that has been safely saved, and if the process fails or restarts, the consumer reverts to that offset. Consumers can choose to automatically commit offsets on a regular basis, or they can choose to manually control by invoking the commit API (for example, Commitsync and Commitasync). The above code is the auto-commit offset.
The difference is that consumers control when a message is considered to have been consumed, control over the consumer, and we discuss it further in more detail below.
- Consumer groups and Topic subscriptions
Kafka's consumer group concept, dividing consumption and processing messages through process pooling. These processes can be run on the same machine or distributed across multiple machines, increasing scalability and fault tolerance, and consumers of the same group.id will be treated as one consumer group.
Each consumer in the group subscribes to a topic list dynamically through the Subscribe API. Kafka messages that have subscribed to topic are sent to each consumer group. And the average is achieved by balancing the partitions among all the members of the consumer group. So each partition happens to allocate exactly 1 consumers (one consumer group). All if a topic has 4 partitions, and a consumer group has 2 consumers. Then each consumer consumes 2 partitions.
The members of the consumer group are dynamically maintained: if a consumer fails. The partition assigned to it is reassigned to other consumers in the same group. Similarly, if a new consumer joins the group, it will be moved from the existing consumer one to it. This is referred to as the rebalance grouping and is discussed in more detail below. The new partition is also rebalanced when it is added to the subscription's topic, or when a new topic is created that matches the regular expression of the subscription. New partitions are automatically discovered and assigned to the members of the group by a timed refresh.
Conceptually , you can treat consumer groupings as a single logical subscriber composed of multiple processes. As a multi-subscription system, Kafka supports any number of consumer groups for a given topic, not duplicates.
This is a slight generalization of the features common in the messaging system. All processes will be part of a single consumer grouping (similar to the semantics of queues in traditional messaging systems), so messaging is like a queue, balanced in groups. Unlike traditional messaging systems, though, you can have multiple such groups. But each process has its own group of consumers (similar to the semantics of pub-sub in a traditional messaging system), so each process subscribes to all messages for that topic.
In addition, when packet reallocation occurs automatically, consumers can be notified via Consumerrebalancelistener, which allows them to complete the necessary application-level logic, such as state cleanup, manual offset submission, and so on. For more details, see offset for Kafka storage.
It also allows the consumer to manually assign a specified partition by using assign (Collection), and if the allocation partition is manually specified, dynamic partition allocation and coordination of the consumer group will expire.
- Discover consumer Failures
After subscribing to a set of topic, when poll (long) is called, the consumer is automatically added to the group. As long as the poll is called continuously, the consumer remains available and continues to receive messages from the allocated partition. In addition, the consumer sends a heartbeat to the server regularly. If the consumer crashes or fails to send a heartbeat within the session.timeout.ms configured time, the consumer will be considered dead and its partition will be reassigned.
There is also the possibility that consumption may encounter a "live lock" situation, which continues to send heartbeats, but is not processed. To prevent consumers from holding partitions in this case, we use the max.poll.interval.ms active detection mechanism. On this basis, if you call the poll frequency greater than the maximum interval, the client will voluntarily leave the group so that other consumers can take over the partition. When this happens, you will see the offset commit failure (call Commitsync () to raise the Commitfailedexception). This is a security mechanism that guarantees that only active members can submit offset. So to stay in the group, you have to keep calling poll.
The consumer provides two configuration settings to control the poll loop:
-
Max.poll.interval.ms: Increases the poll interval, which provides consumers with more time to process the returned messages (calls to poll (long) return messages, usually a batch of messages returned). The disadvantage is that the larger the value, the longer the group is rebalanced.
-
Max.poll.records: This setting limits the number of messages returned per call to poll, which makes it easier to predict the maximum value to be processed for each poll interval. By adjusting this value, you can reduce the poll interval, reducing the number of rebalance groupings
These options are not sufficient for scenarios in which the message processing time is unpredictable. The recommended way to handle this situation is to move the message processing to another thread, allowing the consumer to continue calling poll. However, care must be taken to ensure that the submitted offset does not exceed the actual location. In addition, you must disable autocommit and only manually commit offsets for records (depending on you) only after the thread has finished processing. Also note that you need pause to pause the partition, do not receive a new message from poll, let the thread finish processing the message that was returned (if your processing power is slower than pull cancellation, then creating a new thread will cause your machine memory overflow).
- Controlling the location of consumption
In most cases, consumers are simply consuming messages from start to finish, periodically submitting locations (either automatically or manually). Kafka also support consumers to manually control the location of consumption, can be consumed before the message can also skip the recent message.
There are several situations where it may be useful to manually control the position of the consumer.
One scenario is for time-sensitive consumer handlers, to skip directly to consumers who are lagging enough and start spending from the latest consumption.
Another usage scenario is a local state storage system. In such a system, the consumer is going to initialize its location at startup (whether or not the local store contains it). Similarly, if the local state has been compromised (assuming that the disk is missing), it can be recreated on the new machine by re-consuming all the data and recreating the state (assuming that Kafka retains enough history).
Kafka uses Seek (Topicpartition, long) to specify a new consumption location. The special methods used to find the oldest and newest offset reserved by the server are also available (seektobeginning (Collection) and Seektoend (Collection)).
If a consumer allocates multiple partitions and consumes all the partitions at the same time, the partitions have the same priority. In some cases, consumers need to first consume some of the specified partitions, and when the specified partition has little or no data to consume, it begins to consume other partitions.
For example stream processing, when the processor gets the message from 2 topic and merges the two topic messages, when one of the topic lags behind the other for a long time, the consumption is paused so that the lag catches up.
Kafka supports dynamic control of consumption traffic, using pause (Collection) and resume (Collection) in the Future poll (long) to pause consumption of the specified allocated partition and restart consumption of the specified paused partition.
Kafka----Kafka Java operation and configuration information explained