Kafka生产消费流程
1.Kafka一条消息发送和消费的流程图(非集群)
2.三种发送方式
- 准备工作
创建maven工程,引入依赖
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>3.3.1</version>
</dependency>
- 消费者
/**
* 类说明:消费者入门
*/
public class HelloKafkaConsumer {
public static void main(String[] args) {
// 设置属性
Properties properties = new Properties();
// 指定连接的kafka服务器的地址
properties.put("bootstrap.servers","192.168.140.103:9092");
// 设置String的反序列化
properties.put("key.deserializer", StringDeserializer.class);
properties.put("value.deserializer", StringDeserializer.class);
// 设置消费者组id
properties.put(ConsumerConfig.GROUP_ID_CONFIG,"llp_consumerA");
// 构建kafka消费者对象
KafkaConsumer<String,String> consumer = new KafkaConsumer<String, String>(properties);
try {
//指定消费者订阅的主题
consumer.subscribe(Collections.singletonList("llp-topic"));
// 调用消费者拉取消息
while(true){
// 设置1秒的超时时间
ConsumerRecords<String, String> records= consumer.poll(Duration.ofSeconds(1));
for(ConsumerRecord<String, String> record:records){
String key = record.key();
String value = record.value();
//分区
int partition = record.partition();
System.out.println("接收到消息: partition="+partition+", key = " + key + ", value = " + value);
}
}
} finally {
// 释放连接
consumer.close();
}
}
}
1.1 发送并忘记
忽略send方法的返回值,不做任何处理。大多数情况下,消息会正常到达,而且生产者会自动重试,但有时会丢失消息。
消费者
/**
* 类说明:kafak生产者
*/
public class HelloKafkaProducer {
public static void main(String[] args) {
// 设置属性
Properties properties = new Properties();
// 指定连接的kafka服务器的地址,9092kafka默认端口
properties.put("bootstrap.servers","192.168.140.103:9092");
//补充一下: 配置多台的服务 用,分割, 其中一个宕机,生产者 依然可以连上(集群)
// 设置String的序列化 (对象-》二进制字节数组 : 能够在网络上传输 )
properties.put("key.serializer", StringSerializer.class);
properties.put("value.serializer", StringSerializer.class);
// 构建kafka生产者对象
KafkaProducer<String,String> producer = new KafkaProducer<String, String>(properties);
try {
ProducerRecord<String,String> record;
try {
// 构建消息
record = new ProducerRecord<String,String>("llp-topic", "nickname","llp0");
// 发送消息
producer.send(record);
System.out.println("消息发送成功");
} catch (Exception e) {
e.printStackTrace();
}
} finally {
// 释放连接
producer.close();
}
}
}
测试结果
1.2同步发送
/**
* 类说明:发送消息--同步模式
*/
public class SynProducer {
public static void main(String[] args) {
// 设置属性
Properties properties = new Properties();
// 指定连接的kafka服务器的地址
properties.put("bootstrap.servers","192.168.140.103:9092");
// 设置String的序列化
properties.put("key.serializer", StringSerializer.class);
properties.put("value.serializer", StringSerializer.class);
// 构建kafka生产者对象
KafkaProducer<String,String> producer = new KafkaProducer<String, String>(properties);
try {
ProducerRecord<String,String> record;
try {
// 构建消息
record = new ProducerRecord<String,String>("llp-topic", "llp","同步发送");
// 发送消息
Future<RecordMetadata> future =producer.send(record);
RecordMetadata recordMetadata = future.get();
if(null!=recordMetadata){
System.out.println("偏移量offset:"+recordMetadata.