写一段springboot kafka消费工厂类和动态topic的方法
时间: 2024-09-12 08:06:18 浏览: 40
在Spring Boot应用中,使用Kafka作为消息队列,你可以创建一个消费者Factory类来生产KafkaConsumer实例,并通过注解配置动态订阅主题。这里是一个基础的示例:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.support.destination.TopicPattern;
import org.springframework.stereotype.Component;
@Component
public class KafkaConsumerFactory {
@Autowired
private ConsumerFactory<String, String> consumerFactory;
public void consumeFromDynamicTopics(TopicPattern topicPattern) {
// 创建一个Kafka Consumer实例,支持按照TopicPattern动态订阅
List<TopicPartition> partitions = consumerFactory.createConsumer().subscribe(topicPattern);
while (true) {
ConsumerRecords<String, String> records = consumerFactory.createConsumer().poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> record : records) {
System.out.printf("Received message: %s from topic %s%n", record.value(), record.topic());
// 这里可以添加处理消息的具体业务逻辑
}
}
}
阅读全文