Kafka client libraries include AdminClient class, which can be used for managing and inspecting topics and configuration. You can find the class documentation here: https://kafka.apache.org/21/javadoc/index.html?org/apache/kafka/clients/admin/AdminClient.html.

Here's an example that uses the interface to change the retention period for an existing topic t-topic to 30 minutes (1800000ms):

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.AlterConfigsResult;
import org.apache.kafka.clients.admin.Config;
import org.apache.kafka.clients.admin.ConfigEntry;
import org.apache.kafka.common.config.ConfigResource;
import org.apache.kafka.common.config.TopicConfig;


public class AlterTopic {

    public static void main(String[] args) throws Exception {
        Properties props = new Properties();
        props.put("bootstrap.servers", "demo-kafka.htn-aiven-demo.aivencloud.com:17072");
        props.put("security.protocol", "SSL");
        props.put("ssl.keystore.type", "PKCS12");
        props.put("ssl.keystore.location", "client.keystore.p12");
        props.put("ssl.keystore.password", "changeit");
        props.put("ssl.key.password", "changeit");
        props.put("ssl.truststore.location", "client.truststore.jks");
        props.put("ssl.truststore.password", "changeit");
        AdminClient kafkaAdminClient = AdminClient.create(props);

        ConfigResource resource = new ConfigResource(ConfigResource.Type.TOPIC, "t-topic");
        ConfigEntry retentionEntry = new ConfigEntry(TopicConfig.RETENTION_MS_CONFIG, "1800000");

        Map<ConfigResource, Config> updateConfig = new HashMap<ConfigResource, Config>();
        updateConfig.put(resource, new Config(Collections.singleton(retentionEntry)));

        AlterConfigsResult alterConfigsResult = kafkaAdminClient.alterConfigs(updateConfig);
        System.out.println(alterConfigsResult.all().get());
    }

}
Did this answer your question?