天天看點

程式設計啟動zookeeper和kafka broker

為了學習或者快速測試,走标準的部署流程用指令行啟動太慢,可以直接用java main函數啟動

maven 依賴 

<!-- https://mvnrepository.com/artifact/io.dropwizard.metrics/metrics-core -->
        <dependency>
            <groupId>io.dropwizard.metrics</groupId>
            <artifactId>metrics-core</artifactId>
            <version>4.1.9</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/org.apache.kafka/kafka -->
        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka_2.13</artifactId>
            <version>2.5.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.kafka/kafka-clients -->
        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka-clients</artifactId>
            <version>2.5.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.6.1</version>
        </dependency>
           

配置檔案下載下傳連結

zookeeper.properties

server.properties

zookeeper啟動類(必須先運作)

public class ZooKeeperMain {

    @SneakyThrows
    public static void main(String[] args) {

        QuorumPeerConfig config = new QuorumPeerConfig();
        InputStream is = ZooKeeperMain.class.getResourceAsStream("/zookeeper.properties");
        Properties p = new Properties();
        p.load(is);
        config.parseProperties(p);
        ServerConfig serverconfig = new ServerConfig();
        serverconfig.readFrom(config);
        new ZooKeeperServerMain().runFromConfig(serverconfig);
    }
}
           

kafkabroker啟動類(必須在ZookeeperMain之後運作)

public class KafkaBrokerMain {

    @SneakyThrows
    public static void main(String[] args) {
        InputStream is = KafkaBrokerMain.class.getResourceAsStream("/server.properties");
        Properties p = new Properties();
        p.load(is);
        is.close();
        KafkaServerStartable kafkaServerStartable = KafkaServerStartable.fromProps(p);
        kafkaServerStartable.startup();
        kafkaServerStartable.awaitShutdown();
    }
}
           

繼續閱讀