一、简介
官网:http://kafka.apache.org/
kafka下载命令:
wget http://mirrors.tuna.tsinghua.edu.cn/apache/kafka/2.4.0/kafka_2.13-2.4.0.tgz
kafka解压
tar -zxvf kafka_2.13-2.4.0.tgz
Apache Kafka与传统消息系统相比,有以下不同:
它被设计为一个分布式系统,易于向外扩展;
它同时为发布和订阅提供高吞吐量;
它支持多订阅者,当失败时能自动平衡消费者;
它将消息持久化到磁盘,因此可用于批量消费,例如ETL,以及实时应用程序。
三、准备工作
ZooKeeper下载:
wget http://mirror.bit.edu.cn/apache/zookeeper/zookeeper-3.5.6/apache-zookeeper-3.5.6-bin.tar.gz
1、启动ZooKeeper
Kafka使用ZooKeeper,所以您需要先启动一个ZooKeeper服务器,如果您还没有。您可以使用随Kafka一起打包的便捷脚本来获取一个快速但是比较粗糙的单节点ZooKeeper实例。
启动命令:
bin/zookeeper-server-start.sh config/zookeeper.properties
这个 zookeeper中主要就3个配置:
# the directory where the snapshot is stored.
dataDir=/usr/local/zookeeper
# the port at which the clients will connect
clientPort=2181
# disable the per-ip limit on the number of connections since this is a non-production config
maxClientCnxns=0
我们需要记住zookeeper的端口 2181,在后面会用到。
2、Kafka基本配置
Kafka在config目录下提供了一个基本的配置文件。为了保证可以远程访问Kafka,我们需要修改两处配置。
打开config/server.properties文件,在很靠前的位置有listeners和 advertised.listeners两处配置的注释,去掉这两个注释,并且根据当前服务器的IP修改如下:
# 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://192.168.1.100:9092
当前服务器IP为192.168.1.100,你需要修改为外网或局域网可以访问到的服务器IP。
3、启动Kafka
接下来启动Kafka服务:启动命令:
bin/kafka-server-start.sh config/server.properties
4、创建 Topic
使用下面的命令创建 Topic。命令:
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test
5、启动一个消费者
在一个新的终端执行下面的命令。命令:
bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning
6、启动生产者
命令:
bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test
启动后,可以输入内容,然后回车。
此时你应该可以在上一个消费者中看到有消息输出。
7、查看 topic 列表
命令:
bin/kafka-topics.sh --list --zookeeper localhost:2181
8、查看描述 topics 信息
命令:
bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic test