Kafka支持Linux和WIndows环境(Windows环境请转移我的另一篇文章-->Windows平台kafka环境的搭建),本文运行环境使用Linux(CentOS)。
一、下载Kafka
Kafka官方地址为:https://kafka.apache.org
Kafka官方文档非常的详细,提供的快速入门也很友好,虽然是英文的,但是看命令就能明白,快速入门地址为:https://kafka.apache.org/quickstart。下面内容基本摘自官方快速入门,建议对比英文原版了解更多。
下载完成后,解压压缩包并进入Kafka目录:
> tar -xzf kafka_2.11-0.10.2.1.tgz
> cd kafka_2.11-0.10.2.1
二、 启动服务器
(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=/tmp/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.16.150:9092
当前服务器IP为192.168.16.150,你需要修改为外网或局域网可以访问到的服务器IP。
(3)启动Kafka
接下来启动Kafka服务:
> bin/kafka-server-start.sh config/server.properties
- 如果你在启动时出现 java.lang.OutOfMemoryError: Map failed
- 打开 bin/kafka-run-class.sh 文件,
- 搜索-XX:+DisableExplicitGC,
- 将这个参数替换为 -XX:+ExplicitGCInvokesConcurrent。
三、创建 Topic
使用下面的命令创建 Topic。
> bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test
除了命令方式外,使用后面介绍的Kafka-manager可以更方便的创建。
启动一个消费者,在一个新的终端执行下面的命令。
> bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning
这个消费者就是简单的将消息输出到控制台。
启动生产者
> bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test
启动后,可以输入内容,然后回车。
此时你应该可以在上一个消费者中看到有消息输出。