Kafka Topic Api

Pom:

<dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka_2.10</artifactId>
            <version>0.10.1.0</version>
</dependency>

JavaCode:

package com;


import kafka.admin.AdminUtils;
import kafka.admin.RackAwareMode;
import kafka.server.ConfigType;
import kafka.utils.ZkUtils;
import org.apache.kafka.common.security.JaasUtils;
import org.junit.Test;
import scala.collection.JavaConversions;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 *
 *
 * 测试kafka Topic CRUD
 * @author chenwen
 *
 */
public class TestKafkaApi {

    /**
     *
     * 创建topic
     */
    @Test
    public void createTopic() {
        ZkUtils zkUtils = ZkUtils.apply("172.16.11.224:2181", 30000, 30000, JaasUtils.isZkSecurityEnabled());
        // 创建一个单分区单副本名为test的topic
        AdminUtils.createTopic(zkUtils, "test",
                1,   // 分区数
                1,  // 副本数
                new Properties(),
                RackAwareMode.Enforced$.MODULE$);
        zkUtils.close();
    }

    /**
     *
     * 删除topic
     *
     */
    @Test
    public void deleteTopic() {
        ZkUtils zkUtils = ZkUtils.apply("172.16.11.224:2181", 30000, 30000, JaasUtils.isZkSecurityEnabled());
        // 删除topic 'test'
        AdminUtils.deleteTopic(zkUtils, "test");
        zkUtils.close();
    }

    /**
     *
     * 查询某个topic的属性
     *
     */
    @Test
    public void query() {
        ZkUtils zkUtils = ZkUtils.apply("172.16.11.224:2181", 30000, 30000, JaasUtils.isZkSecurityEnabled());
        // 获取topic 'test'的topic属性属性
        Properties props = AdminUtils.fetchEntityConfig(zkUtils, ConfigType.Topic(), "__consumer_offsets");
        // 查询topic-level属性
        Iterator it = props.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry entry=(Map.Entry)it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            System.out.println(key + " = " + value);
        }
        zkUtils.close();
    }


    /**
     *
     * 判断某个topic是否存在
     *
     * @param topicName
     */
    @Test
    public void topicExists(String topicName) {
        ZkUtils zkUtils = ZkUtils.apply("zkHost", 30000, 30000, JaasUtils.isZkSecurityEnabled());
        boolean exists = AdminUtils.topicExists(zkUtils,topicName);
    }

    /**
     *
     * 获取topiclist
     */
    @Test
    public void getTopicList() {
        ZkUtils zkUtils = ZkUtils.apply("zkHost", 30000, 30000, JaasUtils.isZkSecurityEnabled());
        List<String> allTopicList = JavaConversions.seqAsJavaList(zkUtils.getAllTopics());
    }

}

 

转载于:https://www.cnblogs.com/unclecc/p/10002112.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值