Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java set Kafka retention time in source code

I have the following problem. I need to set the retention time in Kafka for certain selected topics. I found a solution where I can set it with the following command:

kafka-topics --zookeeper localhost:2181 --alter --topic topic-name --config retention.ms=-1

I checked in Kafka's Web UI and confirmed that it got changed.

If possible, I want to set the retention time in Java myself, but I can't seem to find the appropriate class/configuration to set the time. I thought I could get the information about the retention in the ProducerConfig class, but I couldn't find it there.

Is it even possible to set the retention time in Java and if possible, how can I get it done?

Thanks in advance!

like image 840
goku736 Avatar asked Dec 07 '25 08:12

goku736


1 Answers

This works for me :)

    private void setRetentionTime(String topicName, int retentionTime) {
        ConfigResource resource = new ConfigResource(Type.TOPIC, topicName);

        Collection<ConfigEntry> entries = new ArrayList<>();
        entries.add(new ConfigEntry(TopicConfig.RETENTION_MS_CONFIG, String.valueOf(retentionTime)));

        Config config = new Config(entries);
        Map<ConfigResource, Config> configs = new HashMap<>();
        configs.put(resource, config);

        AdminClient client = kafkaConfig.createAdminClient();
        client.alterConfigs(configs);
    }
like image 89
goku736 Avatar answered Dec 08 '25 21:12

goku736