Kafka basic principles

table of Contents

About architecture Kafka Kafka Kafka delete storage policy strategy Kafka brokerKafka DesignThe ProducerThe Consumer copy (Replication) Log Compression (Log Compaction) DistributionZookeeper coordinated control development environment to build some of the example reference

Brief introduction

Apache Kafka is distributed publish - subscribe messaging system. It was originally developed by LinkedIn company later became part of the Apache project. Kafka is a fast, scalable, distributed design is inherent, zoning and submit log service can be replicated.

Kafka architecture

Its architecture includes the following components:

Topic (Topic): a particular type of message flow. The message is byte payload (Payload), the topic is the category name or seed message (Feed) name.

Producers (Producer): the object is to be able to publish any news topic.

Service Agent (Broker): published messages are stored in a set of servers, they are called proxy (Broker) or Kafka cluster.

Consumers (Consumer): you can subscribe to one or more topics, and pull data from the Broker, so consumption of these messages have been posted.

filehttps://images2015.cnblogs.com/blog/434101/201605/434101-20160514145613421-1488903046.png

Kafka storage strategy

1) kafka to topic for message management, each partition comprising a plurality of topic, each logical partition corresponding to a log, consisting of a plurality of segment.

2) Each segment stores a plurality of message (see below), message id determined by its logical position, i.e., may be located directly from the message id of the message to a storage location, to avoid additional location mapping id.

3) Each index corresponds to a part in the memory, each record in the first message segment offset.

4) publisher to send a message topic will be evenly distributed to the plurality of partition (or distributed routing rules specified by the user), Broker adds the message received on the last segment of the release message to the corresponding partition, when the number of news pieces on a segment reaches the configured value or message published exceeds the threshold, the message on the segment will be flush to the disk, a message to subscribers only flush on disk to subscribe to, after the segment reaches a certain size the segment will not go down to write data, broker creates a new segment.

filehttps://images2015.cnblogs.com/blog/434101/201605/434101-20160514145722812-631325437.png

Kafka deletion policy

1) Delete N days ago.

2) retains the latest data MGB.

Kafka broker

Different from other message system, Kafka broker is stateless. This means that consumers must maintain state information has been consumed. This information is maintained by the consumers themselves, broker not care (there are offset managerbroker management).

To delete a message from the agent becomes very difficult, because the agent does not know whether the consumer has been used for the message. Kafka innovative solution to this problem, it will be a simple time-based SLA applies retention policies. When the message broker over a certain time, will be automatically deleted.

This innovative design has a great advantage, consumers can deliberately fall back to the old offset consumption data again. This violates the common agreement of the queue, but it proved to be a basic feature of many consumers.

Kafka Design

aims

1) High throughput to support high-volume event stream processing

2) support load data from the system offline

3) low latency message system

Endurance of

1) depends on the filesystem, persisted to local

2) to log data persistence

effectiveness

1) to solve the "small IO problem": Use "message set" combined message. server using "chunks of messages" written to the log. obtaining a large consumer of the message blocks.

2)解决”byte copying“:在producer、broker和consumer之间使用统一的binary message format。使用系统的pagecache。使用sendfile传输log,避免拷贝。

端到端的批量压缩(End-to-end Batch Compression)Kafka支持GZIP和Snappy压缩协议。

The Producer

负载均衡1)producer可以自定义发送到哪个partition的路由规则。默认路由规则:hash(key)%numPartitions,如果key为null则随机选择一个partition。

2)自定义路由:如果key是一个user id,可以把同一个user的消息发送到同一个partition,这时consumer就可以从同一个partition读取同一个user的消息。

异步批量发送批量发送:配置不多于固定消息数目一起发送并且等待时间小于一个固定延迟的数据。

The Consumer

consumer控制消息的读取。

Push vs Pull1)producer push data to broker,consumer pull data from broker2)consumer pull的优点:consumer自己控制消息的读取速度和数量。3)consumer pull的缺点:如果broker没有数据,则可能要pull多次忙等待,Kafka可以配置consumer long pull一直等到有数据。

Consumer Position1)大部分消息系统由broker记录哪些消息被消费了,但Kafka不是。2)Kafka由consumer控制消息的消费,consumer甚至可以回到一个old offset的位置再次消费消息。

Message Delivery Semantics三种:At most once—Messages may be lost but are never redelivered.At least once—Messages are never lost but may be redelivered.Exactly once—this is what people actually want, each message is delivered once and only once.Producer:有个”acks“配置可以控制接收的leader的在什么情况下就回应producer消息写入成功。

Consumer:读取消息,写log,处理消息。如果处理消息失败,log已经写入,则无法再次处理失败的消息,对应”At most once“。读取消息,处理消息,写log。如果消息处理成功,写log失败,则消息会被处理两次,对应”At least once“。读取消息,同时处理消息并把result和log同时写入。这样保证result和log同时更新或同时失败,对应”Exactly once“。

Kafka默认保证at-least-once delivery,容许用户实现at-most-once语义,exactly-once的实现取决于目的存储系统,kafka提供了读取offset,实现也没有问题。

复制(Replication)

1)一个partition的复制个数(replication factor)包括这个partition的leader本身。

2)所有对partition的读和写都通过leader。

3)Followers通过pull获取leader上log(message和offset)

4)如果一个follower挂掉、卡住或者同步太慢,leader会把这个follower从”in sync replicas“(ISR)列表中删除。

5)当所有的”in sync replicas“的follower把一个消息写入到自己的log中时,这个消息才被认为是”committed“的。

6)如果针对某个partition的所有复制节点都挂了,Kafka选择最先复活的那个节点作为leader(这个节点不一定在ISR里)。

日志压缩(Log Compaction)

1)针对一个topic的partition,压缩使得Kafka至少知道每个key对应的最后一个值。

2)压缩不会重排序消息。

3)消息的offset是不会变的。

4)消息的offset是顺序的。

Distribution

Consumer Offset Tracking

1)High-level consumer记录每个partition所消费的maximum offset,并定期commit到offset manager(broker)。

2)Simple consumer需要手动管理offset。现在的Simple consumer Java API只支持commit offset到zookeeper。

Consumers and Consumer Groups

1)consumer注册到zookeeper

2)属于同一个group的consumer(group id一样)平均分配partition,每个partition只会被一个consumer消费。

3)当broker或同一个group的其他consumer的状态发生变化的时候,consumer rebalance就会发生。

Zookeeper协调控制

1)管理broker与consumer的动态加入与离开。

2) trigger load balancing, when the consumer or to join or leave broker trigger load balancing algorithm such that a plurality of load balancing consumer subscriptions within one consumer group.

3) maintenance of consumer information and consumer relationship of each partition.

Manufacturer Code Example:

import java.util.*;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;

public class TestProducer {

    public static void main(String[] args) {

        long events = Long.parseLong(args[0]);

        Random rnd = new Random();


        Properties props = new Properties();

        props.put("metadata.broker.list", "broker1:9092,broker2:9092 ");

        props.put("serializer.class", "kafka.serializer.StringEncoder");

        props.put("partitioner.class", "example.producer.SimplePartitioner");

        props.put("request.required.acks", "1");


        ProducerConfig config = new ProducerConfig(props);


        Producer<String, Stringproducer = new Producer<String, String(config);


        for (long nEvents = 0; nEvents < events; nEvents  ) {

               long runtime = new Date().getTime();

               String ip = “192.168.2.”   rnd.nextInt(255);

               String msg = runtime   “,www.example.com,”   ip;

               KeyedMessage<String, Stringdata = new KeyedMessage<String, String("page_visits", ip, msg);

               producer.send(data);

        }

        producer.close();

    }

}

Partitioning Code:

import kafka.producer.Partitioner;
import kafka.utils.VerifiableProperties;


public class SimplePartitioner implements Partitioner {

    public SimplePartitioner (VerifiableProperties props) {

    }


    public int partition(Object key, int a_numPartitions) {

        int partition = 0;

        String stringKey = (String) key;

        int offset = stringKey.lastIndexOf('.');

        if (offset 0) {

           partition = Integer.parseInt( stringKey.substring(offset 1)) % a_numPartitions;

        }

       return partition;

  }

}

Consumer Code sample:

import kafka.consumer.ConsumerConfig;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class ConsumerGroupExample {

    private final ConsumerConnector consumer;

    private final String topic;

    private  ExecutorService executor;


    public ConsumerGroupExample(String a_zookeeper, String a_groupId, String a_topic) {

        consumer = kafka.consumer.Consumer.createJavaConsumerConnector(

                createConsumerConfig(a_zookeeper, a_groupId));

        this.topic = a_topic;

    }


    public void shutdown() {

        if (consumer != null) consumer.shutdown();

        if (executor != null) executor.shutdown();

        try {

            if (!executor.awaitTermination(5000, TimeUnit.MILLISECONDS)) {

                System.out.println("Timed out waiting for consumer threads to shut down, exiting uncleanly");

            }

        } catch (InterruptedException e) {

            System.out.println("Interrupted during shutdown, exiting uncleanly");

        }

   }


    public void run(int a_numThreads) {

        Map<String, IntegertopicCountMap = new HashMap<String, Integer();

        topicCountMap.put(topic, new Integer(a_numThreads));

        Map<String, List<KafkaStream<byte[], byte[]consumerMap = consumer.createMessageStreams(topicCountMap);

        List<KafkaStream<byte[], byte[]streams = consumerMap.get(topic);

        // now launch all the threads

        executor = Executors.newFixedThreadPool(a_numThreads);


        // now create an object to consume the messages

        int threadNumber = 0;

        for (final KafkaStream stream : streams) {

            executor.submit(new ConsumerTest(stream, threadNumber));

            threadNumber  ;

        }

    }


    private static ConsumerConfig createConsumerConfig(String a_zookeeper, String a_groupId) {

        Properties props = new Properties();

        props.put("zookeeper.connect", a_zookeeper);

        props.put("group.id", a_groupId);

        props.put("zookeeper.session.timeout.ms", "400");

        props.put("zookeeper.sync.time.ms", "200");

        props.put("auto.commit.interval.ms", "1000");


        return new ConsumerConfig(props);

    }


    public static void main(String[] args) {

        String zooKeeper = args[0];

        String groupId = args[1];

        String topic = args[2];

        int threads = Integer.parseInt(args[3]);


        ConsumerGroupExample example = new ConsumerGroupExample(zooKeeper, groupId, topic);

        example.run(threads);


        try {

            Thread.sleep(10000);

        } catch (InterruptedException ie) {

        }

        example.shutdown();

    }

}

ConsumerTest test class:

import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;


public class ConsumerTest implements Runnable {

    private KafkaStream m_stream;

    private int m_threadNumber;


    public ConsumerTest(KafkaStream a_stream, int a_threadNumber) {

        m_threadNumber = a_threadNumber;

        m_stream = a_stream;

    }


    public void run() {

        ConsumerIterator<byte[], byte[]it = m_stream.iterator();

        while (it.hasNext())

            System.out.println("Thread "   m_threadNumber   ": "   new String(it.next().message()));

        System.out.println("Shutting down Thread: "   m_threadNumber);

    }

}

Development environment to build

https://cwiki.apache.org/confluence/display/KAFKA/Developer Setup

Some example

https://cwiki.apache.org/confluence/display/KAFKA/0.8.0 Producer Example

reference

https://www.cnblogs.com/luxiaoxun/p/5492646.html

https://kafka.apache.org/documentation.html

https://cwiki.apache.org/confluence/display/KAFKA/Index

Published 149 original articles · won praise 66 · views 120 000 +

Guess you like

Origin blog.csdn.net/weixin_38004638/article/details/104088520