HelloKafka
一、启动好zookeeper
二、启动好kafka
三、代码类
HelloKafkaProducer.java
import cn.enjoyedu.config.BusiConst;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import java.util.Properties;
/**
* 类说明:kafka生产者
*/
public class HelloKafkaProducer {
public static void main(String[] args) {
Properties properties=new Properties();
properties.put("bootstrap.servers","127.0.0.1:9092");
properties.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
properties.put("value.serializer","org.apache.kafka.common.serialization.StringSerializer");
KafkaProducer<String,String> producer=new KafkaProducer<String, String>(properties);
ProducerRecord<String,String> record;
//TODO 发送4条消息
try {
for (int i = 0; i < 4; i++) {
record=new ProducerRecord<>(BusiConst.HELLO_TOPIC,"1","lison");
producer.send(record);//发送并忘记
System.out.println(i+"message is send");;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
producer.close();
}
}
}
HelloKafkaConsumer.java
import cn.enjoyedu.config.BusiConst;
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.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.utils.Time;
import java.time.Duration;
import java.util.Collections;
import java.util.Properties;
/**
* 类说明:kafka消费者
*/
public class HelloKafkaConsumer {
public static void main(String[] args) {
// 消费者三个属性必须制定(broker 地址清单、key和value的反序列化器)
Properties properties=new Properties();
properties.put("bootstrap.servers","127.0.0.1:9092");
properties.put("key.deserializer",StringDeserializer.class);
properties.put("value.deserializer",StringDeserializer.class);
//TODO 群组并非完全必须
properties.put(ConsumerConfig.GROUP_ID_CONFIG,"test1");
KafkaConsumer<String,String> consumer=new KafkaConsumer<String, String>(properties);
try {
// 消费者订阅主题(可以多个)
consumer.subscribe(Collections.singletonList(BusiConst.HELLO_TOPIC));
while (true){
//拉取
ConsumerRecords<String,String> records=consumer.poll(Duration.ofMillis(500));
for (ConsumerRecord<String,String> record:records
) {
System.out.println(String.format("topic:%s,分区:%d,偏移量:%d,"+"key:%s,value:%s",record.topic(),record.partition(),
record.offset(),record.key(),record.value()));
}
}
} finally {
consumer.close();
}
}
}