大数据相关

Kafka整理

2018-06-12  本文已影响96人  瑜骐

常用消息中间件对比

kafka

In a very basic structure, a producer publishes messages to a Kafka topic (synonymous with “messaging queue”). A topic is also considered as a message category or feed name to which messages are published. Kafka topics are created on a Kafka broker acting as a Kafka server. Kafka brokers also store the messages if required. Consumers then subscribe to the Kafka topic (one or more) to get the messages. Here, brokers and consumers use Zookeeper to get the state information and to track message offsets, respectively kafka整体图

apache kafka 是一种分布式的,基于发布/订阅的消息系统,由Scala语言编写而成,它具备快速,可扩展,可持久化的特点,其与如下几个主要关键特性有关:

kafka 相关概念

ZooKeeper allows distributed processes to coordinate with each other through a shared hierarchical name space of data registers (we call these registers znodes), much like a file system.

The main differences between ZooKeeper and standard filesystems are that every znode can have data associated with it and znodes are limited to the amount of data that they can have. ZooKeeper was designed to store coordination data: status information, configuration, location information, and so on.

kafka 设计

kafka自定义了一套网络协议,只要遵守这套协议格式,就可以向Kafka发送消息,也可以从Kafka拉取消息。

kafka producer

kafka producer整理处理流程

kafka server

kafka server整体流程

kafka 日志存储

  kafka使用日志文件的方式保存生产者发送的消息,每条消息都有一个offset值来表示它在分区中的偏移量,这个offset值是逻辑值,并不是消息实际存储的物理地址。offset值类似于数据库表中的主键,主键唯一确定了数据库表中的一条记录,offset唯一确定了分区中的一条消息,Kafka对应的逻辑存储机制如下图:

kafka 逻辑存储图  为了提高写入的性能,同一个分区中的消息是顺序写入的,这就避免了随机写入带来的性能问题。一个Topic可以分成多个分区,每一个分区可以有多个副本,当一个分区副本(无论是Leader副本还是Follower副本)被划分到某个Broker上时,Kafka就要在此Broker上为此分区建立相应的Log,而生产者发送的消息会存储在Log中,供消费者拉取后消费。
 Kafka中存储的一般是海量消息数据,为了避免日志文件过大,Log并不是直接对应于磁盘上的一个日志文件,而是磁盘上的一个目录,这个命令的命名规则是<topic_name>_<partition_id>,Log与分区之间的关系是一一对应的,对应分区中的全部消息都存储在此目录下的日志文件中。
 Kafka通过分段的方式将Log分为多个LogSegment,LogSegment是一个逻辑上的概念,一个LogSegment对应磁盘上的一个日志文件和一个索引文件,其中日志文件用于记录消息,索引文件用于保存消息的索引;随着消息的不断写入,日志文件的大小到达一个阈值时,就创建新的日志文件和索引文件继续写入后续的消息和索引信息,日志文件的命名规则是[baseOffset].log,baseOffset是日志文件中第一条消息的offset,如下图所示: Log日志存储
 为了提高查询消息的效率,每个日志文件都对应一个索引文件,这个索引文件并没有为每天消息都建立索引项,而是使用稀疏索引方式为日志文件汇总的部分消息建立索引,如下图所示: Log 日志对应的索引

kafka命令行工具

>>>bin/kafka-server-start.sh config/server.properties
>>>bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic kafkatopic
>>>bin/kafka-console-producer.sh --broker-list localhost:9092 --topic kafkatopic
>>>bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic kafkatopic --from-beginning

参考

  1. Apache kafka源码书籍
  2. Learing apache kafka 书籍
上一篇 下一篇

猜你喜欢

热点阅读