|
| 1 | +package com.lzz.dao.kafka; |
| 2 | + |
| 3 | +import com.google.common.collect.Lists; |
| 4 | +import com.lzz.dao.SourceBase; |
| 5 | +import com.lzz.dao.zk.CuratorClient; |
| 6 | + |
| 7 | +import java.util.*; |
| 8 | + |
| 9 | +/** |
| 10 | + * Created by lzz on 2018/3/19. |
| 11 | + */ |
| 12 | +public class KafkaClient extends SourceBase implements IKafkaClient { |
| 13 | + private static final String CONSUMER_PATH = "/consumers"; |
| 14 | + private Map<String, Set<String>> topicConsumerMap = new HashMap<>(); |
| 15 | + private SourceBase curatorClient; |
| 16 | + |
| 17 | + public KafkaClient(String zk){ |
| 18 | + curatorClient = new CuratorClient(zk); |
| 19 | + initTopicConsumerMap(); |
| 20 | + } |
| 21 | + |
| 22 | + private void initTopicConsumerMap(){ |
| 23 | + |
| 24 | + try { |
| 25 | + List<String> cList = curatorClient.childrenList( CONSUMER_PATH ); |
| 26 | + for(String consumer : cList){ |
| 27 | + List<String> topics = curatorClient.childrenList( CONSUMER_PATH + "/" + consumer + "/offsets" ); |
| 28 | + for(String topic : topics){ |
| 29 | + if( topicConsumerMap.get( topic ) == null ){ |
| 30 | + topicConsumerMap.put( topic, new HashSet<>()); |
| 31 | + } |
| 32 | + topicConsumerMap.get( topic ).add( consumer ); |
| 33 | + } |
| 34 | + } |
| 35 | + } catch (Exception ignore) { |
| 36 | + |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + @Override |
| 41 | + public int getNumChildren(String childPath) throws Exception { |
| 42 | + int childrenNum = 0; |
| 43 | + if( childPath.equals("/") ){ |
| 44 | + childrenNum = getTopicNum(); |
| 45 | + }else if( childPath.split("/").length == 2 ){ |
| 46 | + childrenNum = getConsumerNum(childPath); |
| 47 | + } |
| 48 | + return childrenNum; |
| 49 | + } |
| 50 | + |
| 51 | + @Override |
| 52 | + public List<String> childrenList(String path) throws Exception { |
| 53 | + List<String> cList = new ArrayList<>(); |
| 54 | + if( path.equals("/") ){ |
| 55 | + cList = curatorClient.childrenList("/brokers/topics"); |
| 56 | + }else if( path.split("/").length == 2 ){ |
| 57 | + Set<String> consumerList = topicConsumerMap.get( path.split("/")[1] ); |
| 58 | + cList = Lists.newArrayList(consumerList); |
| 59 | + } |
| 60 | + return cList; |
| 61 | + } |
| 62 | + |
| 63 | + @Override |
| 64 | + public void close() { |
| 65 | + this.curatorClient.close(); |
| 66 | + } |
| 67 | + |
| 68 | + private int getConsumerNum(String childPath) throws Exception { |
| 69 | + String topic = childPath.split("/")[1]; |
| 70 | + int num = 0; |
| 71 | + Set<String> consumerSet = topicConsumerMap.get( topic ); |
| 72 | + if( null != consumerSet ){ |
| 73 | + num = consumerSet.size(); |
| 74 | + } |
| 75 | + return num; |
| 76 | + } |
| 77 | + |
| 78 | + private int getTopicNum() throws Exception { |
| 79 | + int num = curatorClient.getNumChildren("/brokers/topics"); |
| 80 | + return num; |
| 81 | + } |
| 82 | + |
| 83 | +} |
0 commit comments