系统:centos7
下载kafka:http://kafka.apache.org/downloads ,我下载的版本为 kafka_2.11-0.10.1.0.tgz 。
安装ZooKeeper,默认已经安装好 zookeeper-3.4.9 并已经启动。

第1步,下载解压 kafka:

# tar -xzf kafka_2.11-0.10.1.0.tgz 
# cd kafka_2.11-0.10.1.0

第2步,运行 kafka:

kafka的运行是需要ZooKeeper支持的,所以要先启动一个ZooKeeper,但是如果实在不想安装,只是为了小实验,那么kafka也提供了一个便捷的小脚本模拟ZooKeeper运行:

> bin/zookeeper-server-start.sh config/zookeeper.properties

这里我有自己单独的ZooKeeper。

root      59741      1 47 17:17 pts/2    00:00:06 /usr/local/java/jdk1.8.0_131/bin/java -Dzookeeper.log.dir=. -Dzookeeper.root.logger=INFO,CONSOLE -cp /usr/local/zookeeper-3.4.9/bin/../build/classes:/usr/local/zookeeper-3.4.9/bin/../build/lib/*.jar:/usr/local/zookeeper-3.4.9/bin/../lib/slf4j-log4j12-1.6.1.jar:/usr/local/zookeeper-3.4.9/bin/../lib/slf4j-api-1.6.1.jar:/usr/local/zookeeper-3.4.9/bin/../lib/netty-3.10.5.Final.jar:/usr/local/zookeeper-3.4.9/bin/../lib/log4j-1.2.16.jar:/usr/local/zookeeper-3.4.9/bin/../lib/jline-0.9.94.jar:/usr/local/zookeeper-3.4.9/bin/../zookeeper-3.4.9.jar:/usr/local/zookeeper-3.4.9/bin/../src/java/lib/*.jar:/usr/local/zookeeper-3.4.9/bin/../conf:.:/usr/local/java/jdk1.8.0_131/lib/dt.jar:/usr/local/java/jdk1.8.0_131/lib/tools.jar -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.local.only=false org.apache.zookeeper.server.quorum.QuorumPeerMain /usr/local/zookeeper-3.4.9/bin/../conf/zoo.cfg

那么现在使用默认配置文件启动 kafka 的服务:

# /usr/local/kafka_2.11-0.10.1.0/bin/kafka-server-start.sh /usr/local/kafka_2.11-0.10.1.0/config/server.properties

然后会出现一堆默认的配置。。。最后一行再来个 INFO [Kafka Server 0], started (kafka.server.KafkaServer),就完成了。

第3步,创建topic

进入kafka根目录,创建一个单分区单分片名为“test”的topic。

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

然后执行topic的list命令时候,就会列出所有的topic:

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

或者,也可以配置broker的server.property中的auto.create.topics.enable = true,当不存在的主题被发布时,会自动创建该主题。默认是 true。

第4步,生产者发送消息

kafka 附带一个命令行客户端,它将从文件或标准输入中获取输入信息,并将其作为消息发送到 kafka 集群。默认情况下,每一行将作为一个单独的消息发送。
运行生产者程序并发送消息:

# bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test
helo^[[D^H2018
hello2018

第5步,消费者接收消息

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

使用 java 客户端

在使用非本机连接的时候,最好先在 config/server.properties 里面把 listeners 修改一下,否则容易连接失败。

listeners=PLAINTEXT://10.10.22.0:9092

引入jar包

        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka_2.12</artifactId>
            <version>1.0.0</version>
        </dependency>

生产者代码,每秒发送一条数据,topic 不存在会自动创建:

import org.apache.kafka.clients.producer.*;

import java.util.Properties;

public class KafkaProducerDemo {
    private  final Producer<String,String> kafkaProducer;

    public final static String TOPIC="JAVA_TOPIC";

    private KafkaProducerDemo(){
        kafkaProducer=createKafkaProducer() ;
    }
    private Producer<String,String> createKafkaProducer(){
        Properties props = new Properties();
        props.put("bootstrap.servers", "10.10.22.0: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> kafkaProducer = new KafkaProducer<>(props);
        return kafkaProducer;
    }

    void produce(){
        for(int i=1;i<1000;i++){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String key=String.valueOf("key"+i);
            String data="hello kafka message:"+key;
            kafkaProducer.send(new ProducerRecord<>(TOPIC, key, data), new Callback() {
                @Override
                public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                    //do sth
                }
            });
            System.out.println(data);
        }
    }

    public  static  void main(String[] args){
        new KafkaProducerDemo().produce();
    }
}

消费者类代码:

import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import kafka.serializer.StringDecoder;
import kafka.utils.VerifiableProperties;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.util.*;

public class KafkaConsumerDemo {
    private  final KafkaConsumer<String, String> consumer;

    private KafkaConsumerDemo(){
        Properties props = new Properties();
        props.put("bootstrap.servers", "10.10.22.0: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");
        consumer = new KafkaConsumer<>(props);
    }

    void consume(){
        consumer.subscribe(Arrays.asList(KafkaProducerDemo.TOPIC));
        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());
        }
    }

    public  static  void main(String[] args){
        new KafkaConsumerDemo().consume();
    }
}
Logo

Kafka开源项目指南提供详尽教程,助开发者掌握其架构、配置和使用,实现高效数据流管理和实时处理。它高性能、可扩展,适合日志收集和实时数据处理,通过持久化保障数据安全,是企业大数据生态系统的核心。

更多推荐