Kafka : Alter number of partitions for a specific topic using java

前端 未结 1 1215
渐次进展
渐次进展 2021-01-24 02:40

I am new to Kafka and working with new KafkaProducer and KafkaConsumer, version : 0.9.0.1

Is there any way in java to alter/update the number of partitions for a specifi

1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-24 03:30

    Yes, it's possible. You have to access the AdminUtils scala class in kafka_2.11-0.9.0.1.jar to add partitions.

    AdminUtils supports the number of partitions in the topic can only be increased. You may need kafka_2.11-0.9.0.1.jar, zk-client-0.8.jar, scala-library-2.11.8.jar and scala-parser-combinators_2.11-1.0.4.jar jars in your classpath.

    Portions of the below code is borrowed / inspired from kafka-cloudera examples.

    package org.apache.kafka.examples;
    
    import java.io.Closeable;
    
    import org.I0Itec.zkclient.ZkClient;
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    
    import kafka.admin.AdminOperationException;
    import kafka.admin.AdminUtils;
    import kafka.admin.RackAwareMode.Enforced$;
    import kafka.utils.ZKStringSerializer$;
    import kafka.utils.ZkUtils;
    
    public class Test {
    
        static final Logger logger = LogManager.getLogger();
    
        public Test() {
            // TODO Auto-generated constructor stub
        }
    
        public static void addPartitions(String zkServers, String topic, int partitions) {
    
            try (AutoZkClient zkClient = new AutoZkClient(zkServers)) {
                ZkUtils zkUtils = ZkUtils.apply(zkClient, false);
    
                if (AdminUtils.topicExists(zkUtils, topic)) {
                    logger.info("Altering topic {}", topic); 
                    try {
                        AdminUtils.addPartitions(zkUtils, topic, partitions, "", true, Enforced$.MODULE$);
                        logger.info("Topic {} altered with partitions : {}", topic, partitions); 
                    } catch (AdminOperationException aoe) {
                        logger.info("Error while altering partitions for topic : {}", topic, aoe); 
                    } 
                } else {
                    logger.info("Topic {} doesn't exists", topic); 
                } 
            } 
        }
    
        // Just exists for Closeable convenience 
        private static final class AutoZkClient extends ZkClient implements Closeable { 
    
            static int sessionTimeout = 30_000;
            static int connectionTimeout = 6_000;
    
            AutoZkClient(String zkServers) {
                super(zkServers, sessionTimeout, connectionTimeout, ZKStringSerializer$.MODULE$);
            }
        }
    
        public static void main(String[] args) {
    
            addPartitions("localhost:2181", "hello", 20);
        }
    }
    

    0 讨论(0)
提交回复
热议问题