Kafka接收消息

文章目录

java 复制代码
// 采用监听得方式接收 @Payload标记消息体内容.
@KafkaListener(topics = {"test"},groupId = "hello")
public void onEvent(@Payload String event,
                   @Header(value = KafkaHeaders.RECEIVED_TOPIC) String topic,
                   @Header(value = KafkaHeaders.RECEIVED_PARTITION_ID) String partition){
   System.out.println("读取到了时间消息: " + event);
}

Acknowledgment

开启手动确认模式;

java 复制代码
listener:
	ack-mode: manual
java 复制代码
// 采用监听得方式接收 @Payload标记消息体内容.
@KafkaListener(topics = {"test"},groupId = "hello")
public void onEvent(@Payload String event,
                   @Header(value = KafkaHeaders.RECEIVED_TOPIC) String topic,
                   @Header(value = KafkaHeaders.RECEIVED_PARTITION_ID) String partition,
                   ConsumerRecord<String,String> record,
                   Acknowledgment ack){
   ack.acknowledge(); // 手动确认,告诉kafka服务器该消息我已经收到了. 
   System.out.println("读取到了时间消息: " + event);
}

读消息指定分区

java 复制代码
@KafkaListener(groupId = "hello",
           topicPartitions = {
               @TopicPartition(
                       topic = "${kafka.topic.test}",
                       partitions = {"0","1","2"}, // 0 1 2分区不限制偏移量
                       partitionOffsets = { // 3 分区只读 3偏移量之后的; 4分区只读 4偏移量之后的
                               @PartitionOffset(partition = "3",initialOffset = "3"),
                               @PartitionOffset(partition = "4",initialOffset = "3")
                       })
           }
)

批量消费

修改配置

java 复制代码
kafka:
    bootstrap-servers: 192.168.225.128:9092
    listener:
      type: batch
    # 每次读取20条
    consumer:
      max-poll-records: 20

消费者端接收一个List即可

java 复制代码
@KafkaListener(topics = {"hi"},groupId = "batchGroup2")
public void onEvent3(List<ConsumerRecord<String,String>> records){
    System.out.println(records.size());
}

消息拦截

相关推荐
这个DBA有点耶3 小时前
NULL不是空——数据库里最反直觉的设计,90%新人踩过的坑
数据库·mysql·代码规范
这个DBA有点耶5 小时前
AI写的SQL跑崩了生产库,这锅谁背?
数据库·人工智能·程序员
镜舟科技5 小时前
Databricks 再提 LTAP,AI 时代的数据底座为何重回大一统叙事?
数据库·架构·agent
Databend6 小时前
从湖仓升级为 Agent 时代的数据控制面,Snowflake 和 Databricks 有哪些布局
大数据·数据库·agent
ClouGence9 小时前
SQL Server CDC 能放到 Always On 备库读吗?一文讲透原理与实践
数据库·sql server
先吃饱再说1 天前
存储的进化:从 MySQL 到浏览器缓存,数据到底住在哪?
数据库
Nturmoils1 天前
字段太多看不全,ksql 的展开模式和输出控制怎么用
数据库·后端
Databend1 天前
Agent 轨迹分析与归因的数据工程实践
大数据·数据库·agent
这个DBA有点耶1 天前
SQL改写进阶:标量子查询的“隐形代价”与消除实战
数据库·mysql·架构
smallyoung1 天前
数据库乐观锁深度解析:MySQL、PostgreSQL 实战 + Spring Boot 集成指南
数据库·mysql·postgresql