於kafka核心原理的資料,網上有很多,但是如果不自己研究其源碼,永遠是知其然而不知所以然。下面就來演示如何在windows環境下來編譯kafka源碼,並通過IntelliJ IDEA開發工具搭建kafka的源碼環境,以方便在本地通過debug調試來研究kafka的內部實現機制。
具體步驟:
(1)安裝jdk,版本為1.8.0_131,配置JAVA_HOME:
(2)安裝scala,版本為 2.10.6,配置SCALA_HOME:
(3)安裝Gradle,版本為 3.1,配置GRADLE_HOME:
(4)安裝Maven,版本為 3.2.1,配置MAVEN_HOME:
(5)安裝zookeeper,版本為3.4.6(這里為了方便,只在windows下部署了一個單節點的zookeeper,當然你也可以部署一個zookeeper集群)
到zookeeper官網下載壓縮包,解壓到windows的任意磁盤目錄下,將conf目錄下的zoo_sample.cfg復制一份,將其名稱修改為zoo.cfg,然后打開,指定dataDir=D:\\java\\zookeeper-data\\3.4.6-data,比如我的配置如下:
# The number of milliseconds of each tick tickTime=2000 # The number of ticks that the initial # synchronization phase can take initLimit=10 # The number of ticks that can pass between # sending a request and getting an acknowledgement syncLimit=5 # the directory where the snapshot is stored. # do not use /tmp for storage, /tmp here is just # example sakes. dataDir=D:\\java\\zookeeper-data\\3.4.6-data # the port at which the clients will connect clientPort=2181 # the maximum number of client connections. # increase this if you need to handle more clients #maxClientCnxns=60 # # Be sure to read the maintenance section of the # administrator guide before turning on autopurge. # # http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance # # The number of snapshots to retain in dataDir #autopurge.snapRetainCount=3 # Purge task interval in hours # Set to "0" to disable auto purge feature #autopurge.purgeInterval=1
然后雙擊bin目錄下的zkServer.cmd即可啟動zookeeper:
zookeeper啟動后如下圖,默認占用的端口號為2181:
(6)下載kafka源碼。從kafka官網下載源碼包kafka-0.10.0.1-src.tgz,解壓,比如我解壓到了D:\kafka-0.10.0.1-src目錄下,在解壓后的目錄下面通過命令行窗口執行gradle idea命令,然后經過漫長的等待,控制台會出現構建成功的提示,說明kafka源碼編譯完成;
(7)開發工具使用的是IntellJ IDEA 14.1.7(也可以使用其他更高的版本):
(8)在IntelliJ IDEA中安裝scala插件,這里我安裝的插件版本為 1.5.4:
(9)將編譯好的kafka源碼導入到idea開發工具中,導入后的目錄情況:
(10)將config目錄下的log4j.properties文件拷貝到core\src\main\scala\目錄下,方便查看日志:
(11) 修改server.properties文件中的log.dirs=D:\\tmp\\kafka-logs(修改為你自己windows磁盤目錄)
(12)啟動kafka服務器,即運行core\src\main\scala\kafka\Kafka.scala中的main方法,運行前指定啟動參數:
(13)啟動生產者,啟動參數配置:
(14)啟動消費者,啟動參數配置:
(15)在生產者的控制台上輸入消息"hello kafka"並回車:
觀察消費者的控制台上,如果有消息被消費,說明源碼環境搭建成功:
致此,kafka在IntelliJ IDEA中的源碼環境搭建成功。