繁体   English   中英

如何销毁 Spring Kafka 中的消息侦听器对象?

[英]How to destroy objects of Message listener in Spring Kafka?

我在关注这个

创建没有注释且没有 Spring 引导的 KafkaListener

我有一个 API,所以每当调用 API 时,都会使用新的消息侦听器创建一个新容器。 侦听器将获取某些偏移量的消息,然后将其暂停。 在那之后,我不需要它。 但是当 API 被多次命中时,会创建很多对象。 我想销毁无用的物品。

我在想当一个听众空闲一段时间,然后我可以摧毁它。

我怎样才能做到这一点?

提前致谢

代码

public class Listener extends AbstractConsumerSeekAware implements ConsumerAwareMessageListener<String, String> {

    @Override
    public void onMessage(ConsumerRecord<String, String> consumerRecord, Consumer<?, ?> consumer) {
        // pause if certain offset received
    }

}

这是容器

public KafkaMessageListenerContainer<String, String> getContainer(String topic, int partition, long offset) {
        ContainerProperties containerProperties = new ContainerProperties(new TopicPartitionOffset(topic, partition, offset));
        ConsumerFactory<String, String> consumerFactory = new DefaultKafkaConsumerFactory<>(consumerProperties());
        KafkaMessageListenerContainer<String, String> kafkaMessageListenerContainer = new KafkaMessageListenerContainer<>(consumerFactory, containerProperties);
        kafkaMessageListenerContainer.getContainerProperties().setGroupId(UUID.randomUUID().toString());
        kafkaMessageListenerContainer.setAutoStartup(false);
        kafkaMessageListenerContainer.getContainerProperties().setMessageListener(new Listener());
        return kafkaMessageListenerContainer;
}

private Map<String, Object> consumerProperties(){
        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"));
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        return props;
    }

创建这样的容器会禁用许多功能(例如事件发布)。

最好使用 Boot 的自动配置的ConcurrentKafkaListenerContainerFactory来创建容器。

/**
 * Create and configure a container without a listener; used to create containers that
 * are not used for KafkaListener annotations. Containers created using this method
 * are not added to the listener endpoint registry.
 * @param topicPartitions the topicPartitions to assign.
 * @return the container.
 * @since 2.3
 */
C createContainer(TopicPartitionOffset... topicPartitions);

当您不再需要容器时,只需调用container.stop()即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM