Record Listeners

The @KafkaListener annotation provides a mechanism for simple POJO listeners. The following example shows how to use it:

public class Listener {

    @KafkaListener(id = "foo", topics = "myTopic", clientIdPrefix = "myClientId")
public void listen(String data) {
...
} }

This mechanism requires an @EnableKafka annotation on one of your @Configuration classes and a listener container factory, which is used to configure the underlying ConcurrentMessageListenerContainer. By default, a bean with name kafkaListenerContainerFactory is expected. The following example shows how to use ConcurrentMessageListenerContainer:

@Configuration
@EnableKafka
public class KafkaConfig { @Bean
KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<Integer, String>>
kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<Integer, String> factory =
new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
factory.setConcurrency(3);
factory.getContainerProperties().setPollTimeout(3000);
return factory;
} @Bean
public ConsumerFactory<Integer, String> consumerFactory() {
return new DefaultKafkaConsumerFactory<>(consumerConfigs());
} @Bean
public Map<String, Object> consumerConfigs() {
Map<String, Object> props = new HashMap<>();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, embeddedKafka.getBrokersAsString());
...
return props;
}
}

Notice that, to set container properties, you must use the getContainerProperties() method on the factory.

It is used as a template for the actual properties injected into the container.

Starting with version 2.1.1, you can now set the client.id property for consumers created by the annotation.

The clientIdPrefix is suffixed with -n, where n is an integer representing the container number when using concurrency.

Starting with version 2.2, you can now override the container factory’s concurrency and autoStartup properties by using properties on the annotation itself.

The properties can be simple values, property placeholders, or SpEL expressions. The following example shows how to do so:

@KafkaListener(id = "myListener", topics = "myTopic",
autoStartup = "${listen.auto.start:true}", concurrency = "${listen.concurrency:3}")
public void listen(String data) {
...
}

You can also configure POJO listeners with explicit topics and partitions (and, optionally, their initial offsets).

The following example shows how to do so:

@KafkaListener(id = "thing2", topicPartitions =
{ @TopicPartition(topic = "topic1", partitions = { "0", "1" }),
@TopicPartition(topic = "topic2", partitions = "0",
partitionOffsets = @PartitionOffset(partition = "1", initialOffset = "100"))
})
public void listen(ConsumerRecord<?, ?> record) {
...
}

You can specify each partition in the partitions or partitionOffsets attribute but not both.

When using manual AckMode, you can also provide the listener with the Acknowledgment.

The following example also shows how to use a different container factory.

@KafkaListener(id = "cat", topics = "myTopic",
containerFactory = "kafkaManualAckListenerContainerFactory")
public void listen(String data, Acknowledgment ack) {
...
ack.acknowledge();
}

Finally, metadata about the message is available from message headers.

You can use the following header names to retrieve the headers of the message:

KafkaHeaders.RECEIVED_MESSAGE_KEY

KafkaHeaders.RECEIVED_TOPIC

KafkaHeaders.RECEIVED_PARTITION_ID

KafkaHeaders.RECEIVED_TIMESTAMP

KafkaHeaders.TIMESTAMP_TYPE

The following example shows how to use the headers:

@KafkaListener(id = "qux", topicPattern = "myTopic1")
public void listen(@Payload String foo,
@Header(KafkaHeaders.RECEIVED_MESSAGE_KEY) Integer key,
@Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition,
@Header(KafkaHeaders.RECEIVED_TOPIC) String topic,
@Header(KafkaHeaders.RECEIVED_TIMESTAMP) long ts
) {
...
}
Batch listeners

Starting with version 1.1, you can configure @KafkaListener methods to receive the entire batch of consumer records received from the consumer poll.

To configure the listener container factory to create batch listeners, you can set the batchListener property. The following example shows how to do so:

@Bean
public KafkaListenerContainerFactory<?> batchFactory() {
ConcurrentKafkaListenerContainerFactory<Integer, String> factory =
new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
factory.setBatchListener(true); // <<<<<<<<<<<<<<<<<<<<<<<<<
return factory;
}
The following example shows how to receive a list of payloads: @KafkaListener(id = "list", topics = "myTopic", containerFactory = "batchFactory")
public void listen(List<String> list) {
...
}
The topic, partition, offset, and so on are available in headers that parallel the payloads. The following example shows how to use the headers: @KafkaListener(id = "list", topics = "myTopic", containerFactory = "batchFactory")
public void listen(List<String> list,
@Header(KafkaHeaders.RECEIVED_MESSAGE_KEY) List<Integer> keys,
@Header(KafkaHeaders.RECEIVED_PARTITION_ID) List<Integer> partitions,
@Header(KafkaHeaders.RECEIVED_TOPIC) List<String> topics,
@Header(KafkaHeaders.OFFSET) List<Long> offsets) {
...
}

Alternatively, you can receive a List of Message objects with each offset and other details in each message, but it must be the only parameter (aside from optional Acknowledgment, when using manual commits, and/or Consumer parameters) defined on the method.

The following example shows how to do so:

@KafkaListener(id = "listMsg", topics = "myTopic", containerFactory = "batchFactory")
public void listen14(List<Message<?>> list) {
...
} @KafkaListener(id = "listMsgAck", topics = "myTopic", containerFactory = "batchFactory")
public void listen15(List<Message<?>> list, Acknowledgment ack) {
...
} @KafkaListener(id = "listMsgAckConsumer", topics = "myTopic", containerFactory = "batchFactory")
public void listen16(List<Message<?>> list, Acknowledgment ack, Consumer<?, ?> consumer) {
...
}

No conversion is performed on the payloads in this case.

If the BatchMessagingMessageConverter is configured with a RecordMessageConverter, you can also add a generic type to the Message parameter and the payloads are converted. See Payload Conversion with Batch Listeners for more information.

You can also receive a list of ConsumerRecord objects, but it must be the only parameter (aside from optional Acknowledgment, when using manual commits and Consumer parameters) defined on the method. The following example shows how to do so:

@KafkaListener(id = "listCRs", topics = "myTopic", containerFactory = "batchFactory")
public void listen(List<ConsumerRecord<Integer, String>> list) {
...
} @KafkaListener(id = "listCRsAck", topics = "myTopic", containerFactory = "batchFactory")
public void listen(List<ConsumerRecord<Integer, String>> list, Acknowledgment ack) {
...
}

Starting with version 2.2, the listener can receive the complete ConsumerRecords object returned by the poll() method,

letting the listener access additional methods, such as partitions() (which returns the TopicPartition instances in the list) and records(TopicPartition) (which gets selective records).

Again, this must be the only parameter (aside from optional Acknowledgment, when using manual commits or Consumer parameters) on the method.

The following example shows how to do so:

@KafkaListener(id = "pollResults", topics = "myTopic", containerFactory = "batchFactory")
public void pollResults(ConsumerRecords<?, ?> records) {
...
}

If the container factory has a RecordFilterStrategy configured, it is ignored for ConsumerRecords listeners,

with a WARN log message emitted. Records can only be filtered with a batch listener if the <List<?>> form of listener is used.

Annotation Properties

Starting with version 2.0, the id property (if present) is used as the Kafka consumer group.id property,

overriding the configured property in the consumer factory, if present.

You can also set groupId explicitly or set idIsGroup to false to restore the previous behavior of using the consumer factory group.id.

You can use property placeholders or SpEL expressions within most annotation properties, as the following example shows:

@KafkaListener(topics = "${some.property}")

@KafkaListener(topics = "#{someBean.someProperty}",
groupId = "#{someBean.someProperty}.group")

Starting with version 2.1.2, the SpEL expressions support a special token: __listener.

It is a pseudo bean name that represents the current bean instance within which this annotation exists.

Consider the following example:

@Bean
public Listener listener1() {
return new Listener("topic1");
} @Bean
public Listener listener2() {
return new Listener("topic2");
}
Given the beans in the previous example, we can then use the following: public class Listener { private final String topic; public Listener(String topic) {
this.topic = topic;
} @KafkaListener(topics = "#{__listener.topic}",
groupId = "#{__listener.topic}.group")
public void listen(...) {
...
} public String getTopic() {
return this.topic;
} }

If, in the unlikely event that you have an actual bean called __listener,

you can change the expression token byusing the beanRef attribute. The following example shows how to do so:

@KafkaListener(beanRef = "__x", topics = "#{__x.topic}",
groupId = "#{__x.topic}.group")

Starting with version 2.2.4, you can specify Kafka consumer properties directly on the annotation, these will override any properties with the same name configured in the consumer factory. You cannot specify the group.id and client.id properties this way; they will be ignored; use the groupId and clientIdPrefix annotation properties for those.

The properties are specified as individual strings with the normal Java Properties file format: foo:bar, foo=bar, or foo bar.

@KafkaListener(topics = "myTopic", groupId="group", properties= {
"max.poll.interval.ms:60000",
ConsumerConfig.MAX_POLL_RECORDS_CONFIG + "=100"
})

8、Spring-Kafka Recving Messages的更多相关文章

  1. Spring Boot系列 八、集成Kafka

    一.引入依赖 <dependency> <groupId>org.springframework.kafka</groupId> <artifactId> ...

  2. RabbitMQ与java、Spring结合实例详细讲解(转)

    林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 摘要:本文介绍了rabbitMq,提供了如何在Ubuntu下安装RabbitMQ 服务的方法. ...

  3. 一:Spring Boot、Spring Cloud

    上次写了一篇文章叫Spring Cloud在国内中小型公司能用起来吗?介绍了Spring Cloud是否能在中小公司使用起来,这篇文章是它的姊妹篇.其实我们在这条路上已经走了一年多,从16年初到现在. ...

  4. 一、Spring Cloud介绍

    springcloud 介绍 研究了一段时间spring boot了准备向spirng cloud进发,公司架构和项目也全面拥抱了Spring Cloud.在使用了一段时间后发现Spring Clou ...

  5. Spring Kafka和Spring Boot整合实现消息发送与消费简单案例

    本文主要分享下Spring Boot和Spring Kafka如何配置整合,实现发送和接收来自Spring Kafka的消息. 先前我已经分享了Kafka的基本介绍与集群环境搭建方法.关于Kafka的 ...

  6. Spring Kafka整合Spring Boot创建生产者客户端案例

    每天学习一点点 编程PDF电子书.视频教程免费下载:http://www.shitanlife.com/code 创建一个kafka-producer-master的maven工程.整个项目结构如下: ...

  7. Spring Kafka中关于Kafka的配置参数

    #################consumer的配置参数(开始)################# #如果'enable.auto.commit'为true,则消费者偏移自动提交给Kafka的频率 ...

  8. 四、Spring Boot Web开发

    四.Web开发 1.简介 使用SpringBoot: 1).创建SpringBoot应用,选中我们需要的模块: 2).SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可 ...

  9. RabbitMQ与java、Spring结合实例详细讲解

    林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 摘要:本文介绍了rabbitMq,提供了如何在Ubuntu下安装RabbitMQ 服务的方法. ...

  10. 170613、Spring整合RabbitMQ实例

    一.rabbitMQ简介 1.1.rabbitMQ的优点(适用范围)1. 基于erlang语言开发具有高可用高并发的优点,适合集群服务器.2. 健壮.稳定.易用.跨平台.支持多种语言.文档齐全.3. ...

随机推荐

  1. 清理docker容器的日志大小

    Docker容器日志清理 date :2019-04-08  13:57:40 1. 问题 docker容器日志导致主机磁盘空间满了.docker logs -f container_name 发现大 ...

  2. git clean(转载)

    git clean命令用来从你的工作目录中删除所有没有tracked过的文件. git clean经常和git reset --hard一起结合使用. 记住reset只影响被track过的文件, 所以 ...

  3. tomcat架构分析和源码解读

    最近在看<深入分析java web技术内幕>,书中讲解了一部分tomcat的相关知识,我也去查看了一些源码,看了大神们写的代码,我才知道自己就像在做加减乘除一样,这是不行的.还有好多包和类 ...

  4. Java课程寒假之开发记账本软件(网页版)之四

    一.实现基础功能之一(删除) 在删除的功能实现之前,要明白删除的条件是什么,一开始我是以去向和时间作为条件删除,但是删除的语句好像有问题,好像是因为出现了非法字符(应该是中文吧,不太清楚,因为这不是我 ...

  5. mybatis04--Mapper动态代理实现

    通过之前的操作,我们发现dao的实现类其实并没有做什么实质性的工作,仅仅是通过sqlSession的相关API定位到StudentMapper映射文件 中的ID中的sql语句,其实真正操作DB的是ma ...

  6. 前端上传 base64 编码图片到七牛云存储

    参考文档 如何上传base64编码图片到七牛云 调试过程 文档中分别有 java 和 html 的 demo,可以根据文档示例调试. 下面是我调试的过程,可以作为参考,特别注意的是,如果需要给文件起名 ...

  7. java 中的 Comparable 和 Comparator 与 Iterable 和 Iterator

    Comparable 和 Comparator Comparable 和 Comparator 是两个关系不大的类,其分别侧重于不同的方面. 其中,接口 Comparable<T> 强行对 ...

  8. python全栈开发 * 22 面向对象 知识点汇总 * 180703

    22 面向对象 -----属性,类方法,静态方法,反射一.属性1.属性的定义:将方法伪装成属性,虽然在代码层面上没有任何高深之处,但让其看起来更合理. (类似于属性的方法)class Person: ...

  9. 个人小爱好:Operating System: three easy pieces—第6章第3小节问题2#进程间的切换

    问题2#:进程间的切换 直接执行的下一个问题是如何实现进程的切换.进程的切换按理说是挺简单的,对吧?不就是决定哪一个进程应该停止,哪一进程应该开始而已,才多大点事情啊?但,事实上这还真的有点棘手:尤其 ...

  10. js多选下拉框

    1.js原生实现 1.1:引用JS文件 /*! jQuery v1.12.4 | (c) jQuery Foundation | jquery.org/license */ !function(a,b ...