kafka學習記錄集
阿新 • • 發佈:2019-02-03
kafka筆記一
(本人是kafka小白,想把自己的筆記記錄下來,慢慢學習,逐漸成長)
一、首先安裝kafka叢集,最近最新版本是1.0,下載kafka1.0安裝包,解壓縮,修改配置檔案,安裝,測試,詳見另一篇部落格筆記:kafka叢集安裝部署
二、完成kafka訊息訂閱三劍客:producer生產者、broker中介軟體、consumer消費者
三、利用kafkaAPI編寫生產消費demo
(1)建立maven專案,pom檔案中新增kafka依賴包
<dependency>
<groupId>org.apache.kafka</groupId >
<artifactId>kafka-clients</artifactId>
<version>1.0.0</version>
</dependency>
(2)寫生產者程式
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer .Producer;
import java.util.Properties;
public class kafka_producer {
public static void main(String[] args){
//配置資訊
Properties props = new Properties();
props.put("bootstrap.servers", "寫上自己的叢集IP:port")
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<=50;i++){
String s = "send message : "+i;
producer.send(new ProducerRecord<String,String>("test1",Integer.toString(i), s));
}
producer.close();
}
}
(3)現在在後端切到kafka安裝目錄的bin目錄下,執行kafka的消費者命令
./kafka-console-consumer.sh --bootstrap-server 你的ip:port --topic 你的topic --from-beginning
執行生產者程式,觀察到後端kafka服務中consumer在消費訊息。
注:保證topic一致,保證kafka叢集正常啟動。
(4)消費者demo
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import java.util.Arrays;
import java.util.Properties;
public class kafka_consumer {
public static void main(String[] args){
Properties props = new Properties();
props.put("bootstrap.servers", "your ip:port")
props.put("group.id", "my_group");
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");
KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);
consumer.subscribe(Arrays.asList("test1"));
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());
}
}
}
依據kafkaAPI, 簡單的實現了生產消費程序,後續會繼續學習,共勉!