Kafka 架构与分布式使用

名词解释

  • Broker

Kafka集群包含一个或多个服务器,这种服务器被称为broker。

  • Topic

每条发布到Kafka集群的消息都有一个类别,这个类别被称为Topic。(物理上不同Topic的消息分开存储,逻辑上一个Topic的消息虽然保存于一个或多个broker上但用户只需指定消息的Topic即可生产或消费数据而不必关心数据存于何处)。

  • Partition

Parition是物理上的概念,每个Topic包含一个或多个Partition。

  • Producer

负责发布消息到Kafka broker

  • Consumer

消息消费者,向Kafka broker读取消息的客户端。

  • Consumer Group

每个Consumer属于一个特定的Consumer Group(可为每个Consumer指定group name,若不指定group name则属于默认的group)。

物理拓扑图

kafka architecture 架构

  如上图所示,一个典型的Kafka集群中包含若干Producer(可以是web前端产生的Page View,或者是服务器日志,系统CPU、Memory等),若干broker(Kafka支持水平扩展,一般broker数量越多,集群吞吐率越高),若干Consumer Group,以及一个Zookeeper集群。Kafka通过Zookeeper管理集群配置,选举leader,以及在Consumer Group发生变化时进行rebalance。Producer使用push模式将消息发布到broker,Consumer使用pull模式从broker订阅并消费消息。

分布式Kafka搭建

  • ZooKeeper

    Kafka通过ZooKeeper管理。每个Kafka server都有一个broker id,在配置文件server.properties中配置:

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

    启动Kafka后,在ZooKeeper上创建节点位于:/brokers/ids。查看某个broker得到如下结果:

    [zk: localhost:2181(CONNECTED) 7] get /brokers/ids/0
    {"listener_security_protocol_map":{"PLAINTEXT":"PLAINTEXT"},"endpoints":["PLAINTEXT://orisonchan:9092"],"jmx_port":-1,"host":"orisonchan","timestamp":"1517127677270","port":9092,"version":4}
    

    其中,endpoint可在server.properties配置:

    # 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
    

    可以看到,默认监听producer端口和广播给consumer端口都是9092。

Topic&Partition

  Topic在逻辑上可以被认为是一个queue,每条消费都必须指定它的Topic,可以简单理解为必须指明把这条消息放进哪个queue里。为了使得Kafka的吞吐率可以线性提高,物理上把Topic分成一个或多个Partition,每个Partition在物理上对应一个文件夹,该文件夹下存储这个Partition的所有消息和索引文件。

命令行创建topic

bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 3 --partitions 3 --topic test
  • –zookeeper:指定ZooKeeper地址。

  • –topic:topic名。

  • –partitions:分区数。

    如果没有指定分区数,则以shell所在的机器的server.properties的num.partitions参数为准。

  • –replication-factor:副本份数。

    如果有3个partition,3个副本份数,则总共会有9份文件夹。

KafkaTemplate创建topic

  KafkaTemplate是Java API,一般在Spring中或者Spring的某些产品如Spring Data或SpringBoot使用。

  在KafkaTemplate中没有创建topic的API,只要使用send方法发送至Kafka,Kafka发现并没有对应的topic,就会使用默认的num.partitions来创建topic。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值