mav*_*ick 2 apache-kafka spring-boot kafka-consumer-api spring-web spring-kafka
对于我的演示应用程序,我必须创建一个 rest 控制器来返回 kafka 队列中的消息。我已经阅读了 spring-kafka 参考指南并实现了消费者配置并创建了如下的 bean
@Configuration
@EnableKafka
public class ConsumerConfiguration {
@Value("${kafka.bootstrap-servers}")
private String bootstrapServers;
@Bean
public Map<String, Object> consumerConfigs() {
Map<String, Object> props = new HashMap<>();
// list of host:port pairs used for establishing the initial connections to the Kakfa cluster
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);
// allows a pool of processes to divide the work of consuming and processing records
props.put(ConsumerConfig.GROUP_ID_CONFIG, "trx");
return props;
}
@Bean
public ConsumerFactory<String, Transaction> transactionConsumerFactory() {
return new DefaultKafkaConsumerFactory<>(
consumerConfigs(),new StringDeserializer(),new JsonDeserializer<>(Transaction.class)
);
}
@Bean
public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, Transaction>> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, Transaction> factory =
new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(transactionConsumerFactory());
return factory;
}
@Bean
public Consumer consumer() {
return new Consumer();
}
}
Run Code Online (Sandbox Code Playgroud)
和另一个类消费者如下
public class Consumer {
private CountDownLatch latch = new CountDownLatch(1);
public CountDownLatch getLatch() {
return latch;
}
@KafkaListener(topics = "${kafka.topic.name}")
public void receive(Transaction transaction) {
latch.countDown();
}
}
Run Code Online (Sandbox Code Playgroud)
我现在如何实现逻辑以在控制器上每次命中时从消费者处检索事务。
提前致谢。
好吧,@KafkaListener产生独立的长期过程以将记录从 Kafka 流式传输到回调。既然你是在谈论REST GET事件,你没有选择,除非得到KafkaConsumer来自ConsumerFactory其调用poll()从控制器方法手动。
| 归档时间: |
|
| 查看次数: |
1234 次 |
| 最近记录: |