天天看點

kafka掃盲筆記,實戰入門

   Kafka作為大資料時代的産物,自有其生存之道。讓我們跟随掃盲班的教育訓練,進行大緻了解與使用kafka吧。(平時工作有使用不代表就知道kafka了喲)

1. kafka介紹

1.1. 擁有的能力(能幹什麼?)

     根據官網的介紹,ApacheKafka®是一個分布式流媒體平台,它主要有3種功能:

  1. 釋出和訂閱消息流,這個功能類似于消息隊列,這也是kafka歸類為消息隊列架構的原因

  2. 以容錯的方式記錄消息流,kafka以檔案的方式來存儲消息流

  3. 可以再消息釋出的時候進行處理

1.2. 應用場景(在哪些地方适用?)

     1. 作為一種消息中間件,類似于rabbitmq産品,提供消息隊列功能;

     2. 建構實時的流資料處理程式來變換或處理資料流,資料處理功能,重要應用:  Apache Storm;

     3. 使用者行為跟蹤,如pv,uv等等UBT資料跟蹤;

     3. 名額監控,用于業務預警,擁有強悍的吞吐能力;

     4. 日志聚合,叢集日志收集(日志中心),友善系統排障;

1.3. 詳細介紹(功能說明)

     Kafka目前主要作為一個分布式的釋出訂閱式的消息系統使用,下面簡單介紹一下kafka的基本機制

  1.3.1 消息傳輸流程

kafka掃盲筆記,實戰入門

    Producer即生産者,向Kafka叢集發送消息,在發送消息之前,會對消息進行分類,即Topic,上圖展示了兩個producer發送了分類為topic1的消息,另外一個發送了topic2的消息。

    Topic即主題,通過對消息指定主題可以将消息分類,消費者可以隻關注自己需要的Topic中的消息

    Consumer即消費者,消費者通過與kafka叢集建立長連接配接的方式,不斷地從叢集中拉取消息,然後可以對這些消息進行處理。

    從上圖中就可以看出同一個Topic下的消費者和生産者的數量并不是對應的。

  1.3.2 kafka伺服器消息存儲政策

kafka掃盲筆記,實戰入門

    談到kafka的存儲,就不得不提到分區,即partitions,建立一個topic時,同時可以指定分區數目,分區數越多,其吞吐量也越大,但是需要的資源也越多,同時也會導緻更高的不可用性,kafka在接收到生産者發送的消息之後,會根據均衡政策将消息存儲到不同的分區中。

kafka掃盲筆記,實戰入門

  在每個分區中,消息以順序存儲,最晚接收的的消息會最後被消費。

  1.3.3 與生産者的互動

kafka掃盲筆記,實戰入門

    生産者在向kafka叢集發送消息的時候,可以通過指定分區來發送到指定的分區中

    也可以通過指定均衡政策來将消息發送到不同的分區中

    如果不指定,就會采用預設的随機均衡政策,将消息随機的存儲到不同的分區中

  1.3.4  與消費者的互動

kafka掃盲筆記,實戰入門

    在消費者消費消息時,kafka使用offset來記錄目前消費的位置

    在kafka的設計中,可以有多個不同的group來同時消費同一個topic下的消息,如圖,我們有兩個不同的group同時消費,他們的的消費的記錄位置offset各不項目,不互相幹擾。

    對于一個group而言,消費者的數量不應該多餘分區的數量,因為在一個group中,每個分區至多隻能綁定到一個消費者上,即一個消費者可以消費多個分區,一個分區隻能給一個消費者消費

    是以,若一個group中的消費者數量大于分區數量的話,多餘的消費者将不會收到任何消息。

2. Kafka安裝與使用

2.1.  下載下傳

  你可以在kafka官網 http://kafka.apache.org/downloads最新版使用。

2.2. 安裝

  Kafka是使用scala編寫的運作與jvm虛拟機上的程式,雖然也可以在windows上使用,但是kafka基本上是運作在linux伺服器上,是以我們這裡也使用linux來開始今天的實戰。

  首先確定你的機器上安裝了jdk,kafka需要java運作環境,以前的kafka還需要zookeeper,新版的kafka已經内置了一個zookeeper環境,是以我們可以直接使用。自己安裝獨立zk環境也很友善,可參考這篇文章: https://www.cnblogs.com/yougewe/articles/9546233.html

  安裝方法:隻需要解壓到任意目錄就可以使用了(windows環境需要将CLASS_PATH用""雙引号括起來,否則會導緻類查找失敗),這裡我們将kafka壓縮包解壓到/home目錄

2.3. 配置

  在kafka解壓目錄下下有一個config的檔案夾,裡面放置的是我們的配置檔案

  consumer.properites 消費者配置,這個配置檔案用于配置于2.5節中開啟的消費者,此處我們使用預設的即可

  producer.properties 生産者配置,這個配置檔案用于配置于2.5節中開啟的生産者,此處我們使用預設的即可

  server.properties kafka伺服器的配置,此配置檔案用來配置kafka伺服器,目前僅介紹幾個最基礎的配置

    1. broker.id 申明目前kafka伺服器在叢集中的唯一ID,需配置為integer,并且叢集中的每一個kafka伺服器的id都應是唯一的,我們這裡采用預設配置即可
    2. listeners 申明此kafka伺服器需要監聽的端口号,如果是在本機上跑虛拟機運作可以不用配置本項,預設會使用localhost的位址,如果是在遠端伺服器上運作則必須配置,例如:

          listeners=PLAINTEXT:// 192.168.180.128:9092。并確定伺服器的9092端口能夠通路

      3.zookeeper.connect 申明kafka所連接配接的zookeeper的位址 ,需配置為zookeeper的位址,由于本次使用的是kafka高版本中自帶zookeeper,使用預設配置即可

          zookeeper.connect=localhost:2181

2.4. 運作

  1. 啟動zookeeper

cd進入kafka解壓目錄,輸入

bin/zookeeper-server-start.sh config/zookeeper.properties # windows版本需加目錄 windows\xx.bat      

啟動zookeeper成功後會看到如下的輸出

kafka掃盲筆記,實戰入門

    2.啟動kafka

bin/kafka-server-start.sh config/server.properties   # windows版本需加目錄 windows\xx.bat      

啟動kafka成功後會看到如下的輸出

kafka掃盲筆記,實戰入門

2.5. 第一個消息

   2.5.1   建立一個topic

    Kafka通過topic對同一類的資料進行管理,同一類的資料使用同一個topic可以在處理資料時更加的便捷

    在kafka解壓目錄打開終端,建立一個名為test的topic

bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test  # windows版本需加目錄 windows\xx.bat      

         在建立topic後可以通過輸入

bin/kafka-topics.sh --list --zookeeper localhost:2181   # windows版本需加目錄 windows\xx.bat      

來檢視已經建立的topic

  2.4.2   

建立一個消息消費者

   在kafka解壓目錄打開終端,輸入如下指令,建立一個用于消費topic為test的消費者

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

         消費者建立完成之後,因為還沒有發送任何資料,是以這裡在執行後沒有列印出任何資料

         不過别着急,不要關閉這個終端,打開一個新的終端,接下來我們建立第一個消息生産者

  2.4.3 建立一個消息生産者

    在kafka解壓目錄打開一個新的終端,輸入

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

    在執行完畢後會進入的編輯器頁面

kafka掃盲筆記,實戰入門

在發送完消息之後,可以回到我們的消息消費者終端中,可以看到,終端中已經列印出了我們剛才發送的消息

kafka掃盲筆記,實戰入門

   2.4.3       叢集環境下使用kafka

    kafka 做單個執行個體,是沒有存在的意義的,是以讓我們來看看怎麼做快速的叢集部署。

    2.4.3.1  複制出多份server.properties, 進行不同的配置

> cp config/server.properties config/server-1.properties
> cp config/server.properties config/server-2.properties      

    2.4.3.2 各自配置如下:

config/server-1.properties:
    broker.id=1
    listeners=PLAINTEXT://:9093
    log.dirs=/tmp/kafka-logs-1
 
config/server-2.properties:
    broker.id=2
    listeners=PLAINTEXT://:9094
    log.dirs=/tmp/kafka-logs-2      

    2.4.3.3 然後啟動三個叢集broker,現在就已經是叢集環境了

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

    2.4.3.4 向叢集中添加topic

> bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 3 --partitions 1 --topic my-replicated-topic      

    檢視叢集節點情況:

> bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic my-replicated-topic      

    2.4.3.5 發送消息、消費消息,驗證結果

> bin/kafka-console-producer.sh --broker-list localhost:9092 --topic my-replicated-topic
my test message 1
Now let's consume these messages:
> bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --from-beginning --topic my-replicated-topic
my test message 1      

3. 使用java程式對接kafka

    跟上節中一樣,我們現在在java程式中嘗試使用kafka

    3.1  建立Topic

public static void main(String[] args) {
    //建立topic
    Properties props = new Properties();
    props.put("bootstrap.servers", "192.168.180.128:9092");
    AdminClient adminClient = AdminClient.create(props);
    ArrayList<NewTopic> topics = new ArrayList<NewTopic>();
    NewTopic newTopic = new NewTopic("topic-test", 1, (short) 1);
    topics.add(newTopic);
    CreateTopicsResult result = adminClient.createTopics(topics);
    try {
        result.all().get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}      

  使用AdminClient API可以來控制對kafka伺服器進行配置,我們這裡使用NewTopic(String name, int numPartitions, short   replicationFactor)的構造方法來建立了一個名為“topic-test”,分區數為1,複制因子為1的Topic.

3.2  Producer生産者發送消息

public static void main(String[] args){
    Properties props = new Properties();
    props.put("bootstrap.servers", "192.168.180.128:9092");
    props.put("acks", "all");
    props.put("retries", 0);
    props.put("batch.size", 16384);
    props.put("linger.ms", 1);
    props.put("buffer.memory", 33554432);
    props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

    Producer<String, String> producer = new KafkaProducer<String, String>(props);
    for (int i = 0; i < 100; i++)
        producer.send(new ProducerRecord<String, String>("topic-test", Integer.toString(i), Integer.toString(i)));

    producer.close();

}      

  使用producer發送完消息可以通過2.5中提到的伺服器端消費者監聽到消息。也可以使用接下來介紹的java消費者程式來消費消息

3.3 Consumer消費者消費消息

public static void main(String[] args){
    Properties props = new Properties();
    props.put("bootstrap.servers", "192.168.12.65:9092");
    props.put("group.id", "test");
    props.put("enable.auto.commit", "true");
    props.put("auto.commit.interval.ms", "1000");
    props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
    props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
    final KafkaConsumer<String, String> consumer = new KafkaConsumer<String,String>(props);
    consumer.subscribe(Arrays.asList("topic-test"),new ConsumerRebalanceListener() {
        public void onPartitionsRevoked(Collection<TopicPartition> collection) {
        }
        public void onPartitionsAssigned(Collection<TopicPartition> collection) {
            //将偏移設定到最開始
            consumer.seekToBeginning(collection);
        }
    });
    while (true) {
        ConsumerRecords<String, String> records = consumer.poll(100);
        for (ConsumerRecord<String, String> record : records)
            System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
    }
}      

  這裡我們使用Consume API 來建立了一個普通的java消費者程式來監聽名為“topic-test”的Topic,每當有生産者向kafka伺服器發送消息,我們的消費者就能收到發送的消息。

4. 使用spring-kafka

Spring-kafka是正處于孵化階段的一個spring子項目,能夠使用spring的特性來讓我們更友善的使用kafka

4.1 基本配置資訊

與其他spring的項目一樣,總是離不開配置,這裡我們使用java配置來配置我們的kafka消費者和生産者。

  1. 引入pom檔案
<!--kafka start-->
<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka-clients</artifactId>
    <version>0.11.0.1</version>
</dependency>
<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka-streams</artifactId>
    <version>0.11.0.1</version>
</dependency>
<dependency>
    <groupId>org.springframework.kafka</groupId>
    <artifactId>spring-kafka</artifactId>
    <version>1.3.0.RELEASE</version>
</dependency>      
  1. 建立配置類

我們在主目錄下建立名為KafkaConfig的類

@Configuration
@EnableKafka
public class KafkaConfig {
  //topic config Topic的配置開始
    @Bean
    public KafkaAdmin admin() {
        Map<String, Object> configs = new HashMap<String, Object>();
        configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.180.128:9092");
        return new KafkaAdmin(configs);
    }

    @Bean
    public NewTopic topic1() {
        return new NewTopic("foo", 10, (short) 2);
    }
  //topic的配置結束
//producer config start
    @Bean
    public ProducerFactory<Integer, String> producerFactory() {
        return new DefaultKafkaProducerFactory<Integer,String>(producerConfigs());
    }
    @Bean
    public Map<String, Object> producerConfigs() {
        Map<String, Object> props = new HashMap<String,Object>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.180.128:9092");
        props.put("acks", "all");
        props.put("retries", 0);
        props.put("batch.size", 16384);
        props.put("linger.ms", 1);
        props.put("buffer.memory", 33554432);
        props.put("key.serializer", "org.apache.kafka.common.serialization.IntegerSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        return props;
    }
    @Bean
    public KafkaTemplate<Integer, String> kafkaTemplate() {
        return new KafkaTemplate<Integer, String>(producerFactory());
    }
//producer config end

}      
  1. 配置Topic

  在kafkaConfig類中添加配置 

  1. 配置生産者Factort及Template

5.配置ConsumerFactory

//consumer config start
    @Bean
    public ConcurrentKafkaListenerContainerFactory<Integer,String> kafkaListenerContainerFactory(){
        ConcurrentKafkaListenerContainerFactory<Integer, String> factory = new ConcurrentKafkaListenerContainerFactory<Integer, String>();
        factory.setConsumerFactory(consumerFactory());
        return factory;
    }

    @Bean
    public ConsumerFactory<Integer,String> consumerFactory(){
        return new DefaultKafkaConsumerFactory<Integer, String>(consumerConfigs());
    }


    @Bean
    public Map<String,Object> consumerConfigs(){
        HashMap<String, Object> props = new HashMap<String, Object>();
        props.put("bootstrap.servers", "192.168.180.128:9092");
        props.put("group.id", "test");
        props.put("enable.auto.commit", "true");
        props.put("auto.commit.interval.ms", "1000");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.IntegerDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        return props;
    }
//consumer config end

       

4.2  建立消息生産者

//使用spring-kafka的template發送一條消息 發送多條消息隻需要循環多次即可
public static void main(String[] args) throws ExecutionException, InterruptedException {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(KafkaConfig.class);
    KafkaTemplate<Integer, String> kafkaTemplate = (KafkaTemplate<Integer, String>) ctx.getBean("kafkaTemplate");
        String data="this is a test message";
        ListenableFuture<SendResult<Integer, String>> send = kafkaTemplate.send("topic-test", 1, data);
        send.addCallback(new ListenableFutureCallback<SendResult<Integer, String>>() {
            public void onFailure(Throwable throwable) {

            }

            public void onSuccess(SendResult<Integer, String> integerStringSendResult) {

            }
        });
}

       

4.3  建立消息消費者

我們首先建立一個一個用于消息監聽的類,當名為”topic-test”的topic接收到消息之後,我們的這個listen方法就會調用。

public class SimpleConsumerListener {
    private final static Logger logger = LoggerFactory.getLogger(SimpleConsumerListener.class);
    private final CountDownLatch latch1 = new CountDownLatch(1);

    @KafkaListener(id = "foo", topics = "topic-test")
    public void listen(byte[] records) {
        //do something here
        this.latch1.countDown();
    }
}      

我們同時也需要将這個類作為一個Bean配置到KafkaConfig中

@Bean
public SimpleConsumerListener simpleConsumerListener(){
    return new SimpleConsumerListener();
}      

預設spring-kafka會為每一個監聽方法建立一個線程來向kafka伺服器拉取消息。

文章轉載自:https://www.cnblogs.com/hei12138/p/7805475.html

英文官方版快速教程: http://kafka.apache.org/quickstart

不要害怕今日的苦,你要相信明天,更苦!

繼續閱讀