Kafka Basics

Introduction 1. kafka

1.1. The main function

According to the official website of the introduction, ApacheKafka® is a distributed streaming media platform , it has three main functions:

  1:. It lets you publish and subscribe to streams of records publish and subscribe messaging stream, this function is similar to the message queue, which is classified as a reason for the message queue framework kafka

  2:. It lets you store streams of records in a fault-tolerant way in a fault tolerant way to record a message flow, kafka as files stored message flow

  3: When It lets you process streams of records as they occur can be processed further news release

 

1.2. Using the Scene

1:. Building real-time streaming data pipelines that reliably get data between systems or applications to build between the system or application for the reliable transmission of real-time data pipes, message queues function

2: Building real-time streaming applications that transform or react to the streams of data. Construction of real-time streaming data handler to transform or process the data stream, the data processing functions

 

1.3. Details

Kafka mainly as a distributed publish subscribe messaging system, following a brief introduction to the basic mechanisms of kafka

  1.3.1 message transmission process

 

    Producer i.e. producers, Kafka cluster sends a message, before sending the message, the message will be classified, i.e., Topic, the figure shows two producer transmits a message topic1 classified as, in addition to sending a message of topic2.

    Topic That theme, by specifying the theme of the message can categorize messages, consumers can focus on their needs in the Topic of the message

    Consumer i.e. the consumer, the consumer through the establishment of a connection with a long kafka cluster constantly pull message from the cluster, and may process these messages.

    From the above figure can be seen the number of consumers and producers at a same Topic not corresponding.

  1.3.2 kafka server message storage policy

 

    Speaking kafka memory, you have to mention partition, partitions, create a topic, and can specify the number of partitions, the more the number of partitions, greater throughput, but also need more resources, but also does not lead to higher availability, Kafka, after receiving the message sent by the producer, will store the message according to a different partition equilibrium strategy.

 

  In each partition, messages are stored in order, the latest received message was last consumption.

  1.3.3 interact with producers

    When sending a message producer to kafka cluster, you may be transmitted to the specified partition by specifying the partition

    You can also send a message by specifying a balanced policy to different partitions

    If not specified, will use the default random balancing policy, the message is stored in random different partitions

  1.3.4 interact with consumers

  

    When consumer spending news, kafka use offset to record the current position of the consumer

    In kafka design, there may be a plurality of different group message to the consumer while at the same Topic, as shown, we have two different group consumed together, their recording position offset consumption varies, not mutually interference.

    For a group, the number of consumers should not be the number of unnecessary partitions, because in a group, each partition can only be bound up to a consumer that a consumer can consume multiple partitions, only one partition give a consumer spending

    Therefore, if the number of consumers in a group is greater than the number of partitions, then the extra consumers will not receive any messages.

2. Kafka Installation and Use

2.1 Download

  你可以在kafka官网 http://kafka.apache.org/downloads下载到最新的kafka安装包,选择下载二进制版本的tgz文件,根据网络状态可能需要fq,这里我们选择的版本是0.11.0.1,目前的最新版

2.2.  安装

  Kafka是使用scala编写的运行与jvm虚拟机上的程序,虽然也可以在windows上使用,但是kafka基本上是运行在linux服务器上,因此我们这里也使用linux来开始今天的实战。

  首先确保你的机器上安装了jdk,kafka需要java运行环境,以前的kafka还需要zookeeper,新版的kafka已经内置了一个zookeeper环境,所以我们可以直接使用

  说是安装,如果只需要进行最简单的尝试的话我们只需要解压到任意目录即可,这里我们将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

启动zookeeper成功后会看到如下的输出

    2.启动kafka

cd进入kafka解压目录,输入

bin/kafka-server-start.sh config/server.properties

启动kafka成功后会看到如下的输出

 

2.5. 创建第一个消息

   2.5.1 创建一个topic

    Kafka通过topic对同一类的数据进行管理,同一类的数据使用同一个topic可以在处理数据时更加的便捷

    在kafka解压目录打开终端,输入

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

    创建一个名为test的topic

 

         在创建topic后可以通过输入

            bin/kafka-topics.sh --list --zookeeper localhost:2181

   来查看已经创建的topic

  2.5.2 创建一个消息消费者

   在kafka解压目录打开终端,输入

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

   可以创建一个用于消费topic为test的消费者

 

         消费者创建完成之后,因为还没有发送任何数据,因此这里在执行后没有打印出任何数据

         不过别着急,不要关闭这个终端,打开一个新的终端,接下来我们创建第一个消息生产者

  2.5.3 创建一个消息生产者

    在kafka解压目录打开一个新的终端,输入

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

    在执行完毕后会进入的编辑器页面

 

在发送完消息之后,可以回到我们的消息消费者终端中,可以看到,终端中已经打印出了我们刚才发送的消息

 

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服务器发送消息,我们的消费者就能收到发送的消息。

Guess you like

Origin www.cnblogs.com/coco2015/p/11256854.html