kafka入門案例
Conumer_demo1.java內容如下:
package com.lenovo.kafka_demo;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.Properties;
public class Conumer_demo1 extends Thread{
public static void main(String[] args) {
Conumer_demo1 consumerThread = new Conumer_demo1(KafkaProperties.INTOPIC);
consumerThread.start();
}
private final KafkaConsumer<Integer, String> consumer;
private final String topic;
private static final Logger LOG = LoggerFactory.getLogger(Conumer_demo1.class);
public Conumer_demo1(String topic) {
Properties props = new Properties();
//bootstrap.servers 必要
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
KafkaProperties.KAFKA_SERVER_URL + ":" + KafkaProperties.KAFKA_SERVER_PORT0
+ "," + KafkaProperties.KAFKA_SERVER_URL + ":" + KafkaProperties.KAFKA_SERVER_PORT1
+ "," + KafkaProperties.KAFKA_SERVER_URL + ":" + KafkaProperties.KAFKA_SERVER_PORT2);
//group id
props.put(ConsumerConfig.GROUP_ID_CONFIG, "producer-consumer-demo1");
//是否後臺自動提交offset 到kafka
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
//消費者偏移自動提交到Kafka的頻率(以毫秒為單位enable.auto.commit)設定為true
props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
//故障檢測,心跳檢測機制 的間隔時間,,在該值範圍內,沒有接收到心跳,則會刪除該消費者
//並啟動再平衡(rebanlance),值必須在group.min.session.timeout 和 group.max.session.timeout.ms之間
props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "30000");
//key - value 的序列化類
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.IntegerDeserializer");
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
this.consumer = new KafkaConsumer<Integer, String>(props);
this.topic = topic;
}
public void run() {
System.out.println("ConsumerThread--run");
consumer.subscribe(Arrays.asList(KafkaProperties.INTOPIC));//訂閱主題
// consumer.subscribe(Collections.singletonList(this.topic));
while (true) {
//consumer.poll()
ConsumerRecords<Integer, String> records = consumer.poll(200);//在指定的毫秒內一直等待broker返回。
for (ConsumerRecord<Integer, String> record : records) {
System.out.println("Received message: (" + record.key() + ", " + record.value()
+ ") offset " + record.offset()
+ " partition " + record.partition() + ")");
}
}
}
}
Producer_demo1.java中內容如下:
package com.lenovo.kafka_demo;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
/**
*
*/
public class Producer_demo1 extends Thread{
public static void main(String[] args) {
//boolean isAsync = args.length == 0 || !args[0].trim().equalsIgnoreCase("sync");
boolean isAsync = true;
Producer_demo1 producerThread = new Producer_demo1(KafkaProperties.INTOPIC, isAsync);
producerThread.start();
}
private final KafkaProducer<Integer, String> producer;
private final String topic;
private final Boolean isAsync;
public Producer_demo1(String topic, Boolean isAsync) {
Properties props = new Properties();
props.put("bootstrap.servers",
KafkaProperties.KAFKA_SERVER_URL + ":" + KafkaProperties.KAFKA_SERVER_PORT0
+ "," + KafkaProperties.KAFKA_SERVER_URL + ":" + KafkaProperties.KAFKA_SERVER_PORT1
+ "," + KafkaProperties.KAFKA_SERVER_URL + ":" + KafkaProperties.KAFKA_SERVER_PORT2);
props.put("client.id", "Producer_demo1");
//開始的時候下面5個引數未設定,導致消費時取不到資料,需要注意
/* acks=0時,producer不會等待確認,直接新增到socket等待傳送;
acks=1時,等待leader寫到local log就行;
acks=all或acks=-1時,等待isr中所有副本確認
*/
props.put("acks", "all");
//傳送失敗重試
props.put("retries", 0);
//批次傳送,不會嘗試大於此值的容量
props.put("batch.size", 16384);
//預設設定為0,
// 具體引數參考:http://kafka.apache.org/0102/documentation.html#producerconfigs
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");
producer = new KafkaProducer<Integer, String>(props);
//方法傳進來的引數
this.topic = topic;
this.isAsync = isAsync; //非同步的
}
//持續保持資料傳送
public void run() {
System.out.println("ProducerThread--run");
int messageNo = 1;
//這裡面應該是自己的資料邏輯處理
while (true) {
String messageStr = "Message_" + messageNo;
long startTime = System.currentTimeMillis();
/*
檢視原始碼可以知道第二個send其實就是呼叫的第一個send 但是callback為null
send
public Future<RecordMetadata> send(ProducerRecord<K, V> record) {
return this.send(record, (Callback)null);
}
*/
if (isAsync) { // Send asynchronously
producer.send(
new ProducerRecord<Integer, String>(topic, messageNo, messageStr),
new DemoCallBack(startTime, messageNo, messageStr));
} else { // Send synchronously
try {
producer.send(new ProducerRecord<Integer, String>(topic,messageNo,messageStr)).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Sent message: (" + messageNo + ", " + messageStr + ")");
}
//messageNo;
System.out.println("Sent message: (" + messageNo++ + ", " + messageStr + ")");
//休息0.5秒
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(messageNo==5000){
//break;
}
}
}
}
class DemoCallBack implements Callback {
private final long startTime;
private final int key;
private final String message;
public DemoCallBack(long startTime, int key, String message) {
this.startTime = startTime;
this.key = key;
this.message = message;
}
/**
* A callback method the user can implement to provide asynchronous handling of request completion. This method will
* be called when the record sent to the server has been acknowledged. Exactly one of the arguments will be
* non-null.
*
* @param metadata The metadata for the record that was sent (i.e. the partition and offset). Null if an error
* occurred.
* @param exception The exception thrown during processing of this record. Null if no error occurred.
*/
public void onCompletion(RecordMetadata metadata, Exception exception) {
long elapsedTime = System.currentTimeMillis() - startTime;
if (metadata != null) {
System.out.println(
"message(" + key + ", " + message + ") sent to partition(" + metadata.partition() +
"), " +
"offset(" + metadata.offset() + ") in " + elapsedTime + " ms");
} else {
exception.printStackTrace();
}
}
}
KafkaProperties.java內容如下:
package com.lenovo.kafka_demo;
public class KafkaProperties {
public static final String INTOPIC = "producer_consumer_demo1";
//public static final String OUTTOPIC = "topic2";
public static final String KAFKA_SERVER_URL = "127.0.0.1";
public static final int KAFKA_SERVER_PORT0 = 9092;
public static final int KAFKA_SERVER_PORT1 = 9093;
public static final int KAFKA_SERVER_PORT2 = 9094;
public static final int KAFKA_PRODUCER_BUFFER_SIZE = 65536;
public static final int CONNECTION_TIMEOUT = 100000;
public static final String CLIENT_ID = "SimpleConsumerDemoClient";
private KafkaProperties() {}
}
pom.xml內容如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.lenovo</groupId> <artifactId>kafka_demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>kafka_demo</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <kafka.version>0.10.0.1</kafka.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka_2.11</artifactId> <version>${kafka.version}</version> </dependency> </dependencies> </project>
來源:我是碼農,轉載請保留出處和連結!
本文連結:http://www.54manong.com/?id=1228
相關文章
- Kafka 入門Kafka
- Apache Kafka教程--Kafka新手入門ApacheKafka
- Kafka簡單入門Kafka
- Kafka入門(1):概述Kafka
- kafka(docker) 入門分享KafkaDocker
- Kafka基礎入門Kafka
- kafka從入門到關門Kafka
- Kafka 入門與實踐Kafka
- Spring Boot的Kafka入門Spring BootKafka
- kafka快速入門到精通Kafka
- Kafka基礎入門篇Kafka
- Kafka除錯入門(一)Kafka除錯
- vuex入門案例Vue
- Python入門(案例)Python
- RabbitMQ入門案例MQ
- Kafka 入門(四)-- Python Kafka Client 效能測試KafkaPythonclient
- Kafka 入門(三)--為什麼 Kafka 依賴 ZooKeeper?Kafka
- Kafka從入門到放棄(一) —— 初識KafkaKafka
- kafka入門安裝和使用Kafka
- Kafka Streams開發入門(1)Kafka
- 前端-vue入門案例前端Vue
- FineBI入門案例分析
- jQuery入門(四)案例jQuery
- CSS入門案例:摺扇CSS
- Kafka 入門(一)--安裝配置和 kafka-python 呼叫KafkaPython
- Kafka【入門】就這一篇!Kafka
- Kafka入門(4):深入消費者Kafka
- Kafka入門(2):消費與位移Kafka
- Spring Cloud Gateway 入門案例SpringCloudGateway
- webpack 入門之 loader 案例Web
- RabbitMQ 入門案例 - fanout 模式MQ模式
- Python入門經典案例一Python
- MapReduce入門及核心流程案例
- drools的簡單入門案例
- POI-入門案例(2/2)
- 《Kafka入門與實踐》讀書筆記Kafka筆記
- 全網最通俗易懂的Kafka入門!Kafka
- 全網最通俗易懂的Kafka入門Kafka