Apache Kafka 入门

为了方便以后用的到,记录下自己学习的过程。由于没有生产环节使用的经验,希望有经验的朋友可以留言指导。

Apache Kafka 入门大概分为5篇博客,内容都比较基础,计划包含以下内容:

  • Kafka的基本配置和运行
  • Kafka命令详细介绍
  • Kafka-manager的基本配置和运行
  • Kafka API 简单用法
  • Spring Boot 集成Kafka

Kafka支持Linux和WIndows环境,本文运行环境使用Linux(CentOS)。

本篇为第一篇。

Kafka的基本配置和运行

Kafka官方地址为:https://kafka.apache.org

Kafka官方文档非常的详细,提供的快速入门也很友好,虽然是英文的,但是看命令就能明白,快速入门地址为:https://kafka.apache.org/quickstart。下面内容基本摘自官方快速入门,建议对比英文原版了解更多。

1. 下载代码

首先从下面地址下载 Kafka,当前最新的版本为 0.10.2.1。

https://kafka.apache.org/downloads

下载完成后,解压压缩包并进入Kafka目录:

> tar -xzf kafka_2.11-0.10.2.1.tgz
> cd kafka_2.11-0.10.2.1
  • 1
  • 2

2. 启动服务器

(1)启动ZooKeeper

Kafka使用ZooKeeper,所以您需要先启动一个ZooKeeper服务器,如果您还没有。您可以使用随Kafka一起打包的便捷脚本来获取一个快速但是比较粗糙的单节点ZooKeeper实例。

> bin/zookeeper-server-start.sh config/zookeeper.properties
  • 1

这个 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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

我们需要记住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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

当前服务器IP为192.168.16.150,你需要修改为外网或局域网可以访问到的服务器IP。

(3)启动Kafka

接下来启动Kafka服务:

> bin/kafka-server-start.sh config/server.properties
  • 1

如果你在启动时出现 java.lang.OutOfMemoryError: Map failed

打开 bin/kafka-run-class.sh 文件,

搜索-XX:+DisableExplicitGC

将这个参数替换为 -XX:+ExplicitGCInvokesConcurrent

具体原因可以参考: http://blog.csdn.net/xieyuooo/article/details/7547435 。

创建 Topic

使用下面的命令创建 Topic。

> bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test
  • 1

除了命令方式外,使用后面介绍的Kafka-manager可以更方便的创建。

启动一个消费者

在一个新的终端执行下面的命令。

> bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning
  • 1

这个消费者就是简单的将消息输出到控制台。

启动生产者

> bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test
  • 1

启动后,可以输入内容,然后回车。

此时你应该可以在上一个消费者中看到有消息输出。

显示效果如下

下图上方为消费者,只是简单的将消息输出到控制台。下方为生产者,回车时产生消息。

显示效果

到此关于Kafka的基本命令就结束了,接下来是Kafka命令行详细介绍。

猜你喜欢

转载自blog.csdn.net/xinzi11243094/article/details/80198159