1. 程式人生 > >Linux系統中KafKa安裝和使用方法 java客戶端連線kafka

Linux系統中KafKa安裝和使用方法 java客戶端連線kafka

kafka linux單機安裝

1 下載並安裝kafka

# tar zxvf kafka_2.12-1.1.0tgz 
# mv kafka_2.12-1.1.0 /usr/local/kafka
# cd /usr/local/kafka

2 啟動服務

執行kafka需要使用Zookeeper,所以需要先啟動一個Zookeeper伺服器,如果沒有Zookeeper,可以使用kafka自帶打包和配置好的Zookeeper,&後臺程序

# bin/zookeeper-server-start.sh config/zookeeper.properties &

然後啟動kafka服務

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

3 新建一個topic

建立一個名為“test”的Topic,只有一個分割槽和一個備份:

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

建立好之後,可以通過以下命令檢視已建立的topic資訊:

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

除手工建立topic外,也可以配置broker,當釋出一個不存在的topic時自動建立topic。

4 傳送訊息

Kafka提供了一個命令列工具,可以從輸入檔案或者命令列中讀取訊息併發送給Kafka叢集,每一行是一條訊息。執行producer,然後在控制檯輸入幾條訊息到伺服器

# bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test 
This is a message
This is another message

5 消費訊息

Kafka也提供了一個消費訊息的命令列工具

# bin/kafka-console-consumer.sh --zookeeper localhost:2182 --topic test --from-beginning
This is a message
This is another message

append:


listeners=PLAINTEXT://172.16

.49.173:9092


java 客服端連線程式碼

生產者程式碼

import java.util.Properties;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
public class KafkaProducer  {
    private final Producer<String, String> producer;
    public final static String TOPIC = "test";

    private KafkaProducer(){
        Properties props = new Properties();
        //此處配置的是kafka的埠
        props.put("metadata.broker.list", "10.175.118.105:9092");
        //配置value的序列化類
        props.put("serializer.class", "kafka.serializer.StringEncoder");
        //配置key的序列化類
        props.put("key.serializer.class", "kafka.serializer.StringEncoder");
        props.put("request.required.acks","-1");
        producer = new Producer<String, String>(new ProducerConfig(props));
    }

    void produce() {
        int messageNo = 1000;
        final int COUNT = 10000;
        while (messageNo < COUNT) {
            String key = String.valueOf(messageNo);
            String data = "hello kafka message " + key;
            producer.send(new KeyedMessage<String, String>(TOPIC, key ,data));
            System.out.println(data);
            messageNo ++;
        }
    }

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

}

消費者程式碼

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import com.huawei.hwclouds.dbs.ops.base.huatuo.diagnosis.service.impl.KafkaProducer;
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;
public class KafkaConsumer {
    private final ConsumerConnector consumer;

    private KafkaConsumer() {
        Properties props = new Properties();
        //zookeeper 配置
        props.put("zookeeper.connect", "10.175.118.105:2182");

        //group 代表一個消費組
        props.put("group.id", "test-consumer-group");

        //zk連線超時
        props.put("zookeeper.session.timeout.ms", "4000");
        props.put("zookeeper.sync.time.ms", "200");
        props.put("auto.commit.interval.ms", "1000");
        props.put("auto.offset.reset", "smallest");//必須要加,如果要讀舊資料
        //序列化類
        props.put("serializer.class", "kafka.serializer.StringEncoder");

        ConsumerConfig config = new ConsumerConfig(props);
        consumer = kafka.consumer.Consumer.createJavaConsumerConnector(config);
    }

    void consume() {
        Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
        topicCountMap.put(KafkaProducer.TOPIC, new Integer(1));

        StringDecoder keyDecoder = new StringDecoder(new VerifiableProperties());
        StringDecoder valueDecoder = new StringDecoder(new VerifiableProperties());

        Map<String, List<KafkaStream<String, String>>> consumerMap =
                consumer.createMessageStreams(topicCountMap,keyDecoder,valueDecoder);
        KafkaStream<String, String> stream = consumerMap.get(KafkaProducer.TOPIC).get(0);
        ConsumerIterator<String, String> it = stream.iterator();
        while (it.hasNext())
            System.out.println(it.next().message());
    }

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