Linux環境下Kafka的下載配置和運行

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

啓動後,可以輸入內容,然後回車。

此時你應該可以在上一個消費者中看到有消息輸出。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章