1.获取所有topic

package com.example.demo;
import java.io.IOException;
import java.util.List; import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper; public class zookeeper { public static void main(String[] args) {
String connectString = "172.16.10.211:2181";
int sessionTimeout = 4000;
Watcher watcher = new Watcher() {
public void process(WatchedEvent event) {
}
};
try {
ZooKeeper zooKeeper = new ZooKeeper(connectString, sessionTimeout, watcher);
List<String> list = zooKeeper.getChildren("/brokers/topics", false);
int len = list.size();
for(int i = 1;i < len;i++){
System.out.println(list.get(i));
              //此处动态生成消费者
//JavaKafkaConsumerHighAPI example = new JavaKafkaConsumerHighAPI(list.get(i), 1);
//new Thread(example).start();
}
} catch (IOException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

2.参考http://www.cnblogs.com/liuming1992/p/6432626.html生成消费者,这里进行了小小的改造

package com.example.demo;
import kafka.consumer.*;
import kafka.javaapi.consumer.ConsumerConnector;
import kafka.message.MessageAndMetadata;
import kafka.serializer.StringDecoder;
import kafka.utils.VerifiableProperties; import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; /**
* 自定义简单Kafka消费者, 使用高级API
* Created by gerry on 12/21.
*/
public class JavaKafkaConsumerHighAPI implements Runnable {
/**
* Kafka数据消费对象
*/
private ConsumerConnector consumer; /**
* Kafka Topic名称
*/
private String topic; /**
* 线程数量,一般就是Topic的分区数量
*/
private int numThreads; /**
* 线程池
*/
private ExecutorService executorPool; /**
* 构造函数
*
* @param topic Kafka消息Topic主题
* @param numThreads 处理数据的线程数/可以理解为Topic的分区数
* @param zookeeper Kafka的Zookeeper连接字符串
* @param groupId 该消费者所属group ID的值
*/
public JavaKafkaConsumerHighAPI(String topic, int numThreads) {
// 1. 创建Kafka连接器
this.consumer = Consumer.createJavaConsumerConnector(createConsumerConfig("172.16.10.211:2181", "test-consumer-group"));
// 2. 数据赋值
this.topic = topic;
this.numThreads = numThreads;
} @Override
public void run() {
// 1. 指定Topic
Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
topicCountMap.put(this.topic, this.numThreads); // 2. 指定数据的解码器
StringDecoder keyDecoder = new StringDecoder(new VerifiableProperties());
StringDecoder valueDecoder = new StringDecoder(new VerifiableProperties()); // 3. 获取连接数据的迭代器对象集合
/**
* Key: Topic主题
* Value: 对应Topic的数据流读取器,大小是topicCountMap中指定的topic大小
*/
Map<String, List<KafkaStream<String, String>>> consumerMap = this.consumer.createMessageStreams(topicCountMap, keyDecoder, valueDecoder); // 4. 从返回结果中获取对应topic的数据流处理器
List<KafkaStream<String, String>> streams = consumerMap.get(this.topic); // 5. 创建线程池
this.executorPool = Executors.newFixedThreadPool(this.numThreads); // 6. 构建数据输出对象
int threadNumber = 0;
for (final KafkaStream<String, String> stream : streams) {
this.executorPool.submit(new ConsumerKafkaStreamProcesser(stream, threadNumber,topic));
threadNumber++;
}
} public void shutdown() {
// 1. 关闭和Kafka的连接,这样会导致stream.hashNext返回false
if (this.consumer != null) {
this.consumer.shutdown();
} // 2. 关闭线程池,会等待线程的执行完成
if (this.executorPool != null) {
// 2.1 关闭线程池
this.executorPool.shutdown(); // 2.2. 等待关闭完成, 等待五秒
try {
if (!this.executorPool.awaitTermination(5, TimeUnit.SECONDS)) {
System.out.println("Timed out waiting for consumer threads to shut down, exiting uncleanly!!");
}
} catch (InterruptedException e) {
System.out.println("Interrupted during shutdown, exiting uncleanly!!");
}
} } /**
* 根据传入的zk的连接信息和groupID的值创建对应的ConsumerConfig对象
*
* @param zookeeper zk的连接信息,类似于:<br/>
* hadoop-senior01.ibeifeng.com:2181,hadoop-senior02.ibeifeng.com:2181/kafka
* @param groupId 该kafka consumer所属的group id的值, group id值一样的kafka consumer会进行负载均衡
* @return Kafka连接信息
*/
private ConsumerConfig createConsumerConfig(String zookeeper, String groupId) {
// 1. 构建属性对象
Properties prop = new Properties();
// 2. 添加相关属性
prop.put("group.id", groupId); // 指定分组id
prop.put("zookeeper.connect", zookeeper); // 指定zk的连接url
prop.put("zookeeper.session.timeout.ms", "400"); //
prop.put("zookeeper.sync.time.ms", "200");
prop.put("auto.commit.interval.ms", "1000");
// 3. 构建ConsumerConfig对象
return new ConsumerConfig(prop);
} /**
* Kafka消费者数据处理线程
*/
public static class ConsumerKafkaStreamProcesser implements Runnable {
// Kafka数据流
private KafkaStream<String, String> stream;
// 线程ID编号
private int threadNumber;
private String topic; public ConsumerKafkaStreamProcesser(KafkaStream<String, String> stream, int threadNumber,String topic) {
this.stream = stream;
this.threadNumber = threadNumber;
this.topic = topic;
} @Override
public void run() {
// 1. 获取数据迭代器
ConsumerIterator<String, String> iter = this.stream.iterator();
// 2. 迭代输出数据
while (iter.hasNext()) {
// 2.1 获取数据值
MessageAndMetadata value = iter.next(); // 2.2 输出
System.out.println(this.threadNumber + "____" + value.offset() +"_____"+ topic + "____" + value.message());
}
// 3. 表示当前线程执行完成
System.out.println("Shutdown Thread:" + this.threadNumber);
}
}
}

3.pom

<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.11</artifactId>
<version>0.8.2.1</version>
</dependency>

4.

package com.example.text;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.example.es.Es; import kafka.consumer.Consumer;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector; public class KafkaConsumer implements Runnable { private static Logger logger = LoggerFactory.getLogger(KafkaConsumer.class); private Map<String, Integer> topicCountMap;
private Properties props; public KafkaConsumer(Map<String, Integer> topicCountMap, Properties props) {
this.topicCountMap = topicCountMap;
this.props = props;
} @Override
public void run() {
ConsumerConnector consumer = null;
ExecutorService executor = null;
try {
consumer = Consumer.createJavaConsumerConnector(new ConsumerConfig(props));
Map<String, List<KafkaStream<byte[], byte[]>>> msgStreams = consumer.createMessageStreams(topicCountMap);
for (String topic : topicCountMap.keySet()) {
List<KafkaStream<byte[], byte[]>> msgStreamList = msgStreams.get(topic);
// 使用ExecutorService来调度线程
executor = Executors.newFixedThreadPool(topicCountMap.get(topic));
for (int i = 0; i < msgStreamList.size(); i++) {
KafkaStream<byte[], byte[]> kafkaStream = msgStreamList.get(i);
executor.submit(new HanldMessageThread(kafkaStream, i, topic));
}
} } catch (Exception e) {
if (consumer != null) {
consumer.shutdown();
}
if (executor != null) {
executor.shutdown();
}
try {
if (!executor.awaitTermination(5000, TimeUnit.MILLISECONDS)) {
logger.error("Timed out waiting for consumer threads to shutdown, exiting uncleanly");
}
} catch (InterruptedException e1) {
logger.error("Interrupted during shutdown, exiting uncleanly");
}
logger.error(e.getMessage());
}
} } /**
* 具体处理message的线程
*
* @author Administrator
*
*/
class HanldMessageThread implements Runnable { private KafkaStream<byte[], byte[]> kafkaStream = null;
private int num = 0;
private String topic; public HanldMessageThread(KafkaStream<byte[], byte[]> kafkaStream, int num, String topic) {
super();
this.kafkaStream = kafkaStream;
this.num = num;
this.topic = topic;
} public void run() {
ConsumerIterator<byte[], byte[]> iterator = kafkaStream.iterator(); while (iterator.hasNext()) {
String message = new String(iterator.next().message());
// System.out.println(Thread.currentThread().getName());
// System.out.println(this.num + "____" + topic + "____" + message);
// System.out.println(Thread.currentThread().getId());
// System.out.println("Thread no: " + num + ", message: " + message);
if (topic.startsWith("xrs") || topic.startsWith("meitan") || topic.startsWith("qiyexinxi")) {
Es.setData(message, "xrs_db", topic);
} else if (topic.startsWith("search")) {
Es.setData(message, "pholcus_news_v1", topic);
} else {
Es.setData(message, "pholcus_db", topic);
}
}
} }
private static Properties props;

	static {
props = new Properties();
props.put("zookeeper.connect", "172.16.10.211:2181");
props.put("group.id", "test-consumer-group");
props.put("zookeeper.session.timeout.ms", "400");
props.put("zookeeper.sync.time.ms", "200");
props.put("auto.commit.interval.ms", "1000");
} Map<String, Integer> topicCountMap = new HashMap<String, Integer>();

kafka java动态获取topic并动态创建消费者的更多相关文章

  1. Java API获取topic所占磁盘空间(Kafka 1.0.0)

    很多用户都有这样的需求:实时监控某个topic各分区在broker上所占的磁盘空间大小总和.Kafka并没有提供直接的脚本工具用于统计这些数据. 如果依然要实现这个需求,一种方法是通过监控JMX指标得 ...

  2. java最全的获取某个接口或者某个类所有对应的所有实现类和继承类的工具类--反射动态获取、非动态获取、按照路径获取等总结

    我们直接上代码吧,代码中有注释说明. //直接看代码吧 import java.io.File; import java.lang.reflect.Field; import java.net.URL ...

  3. Kafka Java API操作topic

    Kafka官方提供了两个脚本来管理topic,包括topic的增删改查.其中kafka-topics.sh负责topic的创建与删除:kafka-configs.sh脚本负责topic的修改和查询,但 ...

  4. Kafka Java API获取非compacted topic总消息数

    目前Kafka并没有提供直接的工具来帮助我们获取某个topic的当前总消息数,需要我们自行写程序来实现.下列代码可以实现这一功能,特此记录一下: /** * 获取某个topic的当前消息数 * Jav ...

  5. 解决v-html无法理解vue模版的问题-动态获取模版,动态插入app并使用当下app状态数据需求

    很多情况下,我们需要使用动态的html作为某个dom元素的inner html,如果这个内容是标准的html的话,则v-html能够圆满满足需求,而如果内容包含了vue组件,则使用v-html就不能达 ...

  6. Kafka Java consumer动态修改topic订阅

    前段时间在Kafka QQ群中有人问及此事——关于Java consumer如何动态修改topic订阅的问题.仔细一想才发现这的确是个好问题,因为如果简单地在另一个线程中直接持有consumer实例然 ...

  7. java动态获取WebService的两种方式(复杂参数类型)

    java动态获取WebService的两种方式(复杂参数类型) 第一种: @Override public OrderSearchListRes searchOrderList(Order_Fligh ...

  8. java版gRPC实战之六:客户端动态获取服务端地址

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...

  9. (二)Kafka动态增加Topic的副本(Replication)

    (二)Kafka动态增加Topic的副本(Replication) 1. 查看topic的原来的副本分布 [hadoop@sdf-nimbus-perf ~]$ le-kafka-topics.sh ...

随机推荐

  1. JVM垃圾回收补充知识点

    1. 分代 虚拟机中的共划分为三个代: 年轻代(Young Gen):eden和survivor-8:1:1 年老代(Old Gen):存储大对象,由survivor晋升 永久代(perm Gen): ...

  2. CentOS 7 安装oracle 11.2.0.4 Error in invoking target 'agent nmhs' of makefile

    %86时出现报错   Error in invoking target 'agent nmhs' of makefile 解决方案在makefile中添加链接libnnz11库的参数修改$ORACLE ...

  3. 封装一个方法获取url上面的参数

    一.取参   ] : ); ]; ; ]., -); ]) === ]; , , b: 'fdfdfd', c: '9999' })); //a=123546&b=fdfdfd&c=9 ...

  4. 台式机上如何配置并使用苹果iPhone的耳机麦克风 并且麦克风开启降噪功能

    这个资料和技巧在网络上面很少有人分享,但是可能会有不少人需要这个东西.这里分享下经验.这也是一个困扰我很久的一个问题.因为买来了这个转接头,发现,录音的时候iPhone的耳机麦克风有很大的噪音无法消除 ...

  5. 搭建docker registry (htpasswd 认证)

    1,拉取docker registry 镜像 docker pull registry 2,创建证书存放目录 mkdir -p /home/registry 3,生成CA证书Edit your /et ...

  6. myEclipse 常用快捷键,工具等记录

    小的不才,从北大青鸟毕业,出来之后到第一家公司进行工作,当时认为自己很牛逼,很无敌,但是出来之后发现在学校里学的那些东西,在工作中,除了会写一点if...else之外,连循环都很少写. 然而有用的工具 ...

  7. Jenkins 添加节点 java web方式

    环境说明: 主节点:windows server 从节点:两台linux 1. windows server安装jenkins就不多说了,直接添加节点配置如下 2.全局安全配置,指定确认的端口后,记得 ...

  8. ethereum(以太坊)(基础)--容易忽略的坑(三)

    pragma solidity ^0.4.10; contract Byte{ bytes [] public T=new bytes[](3); function setLeng(uint len) ...

  9. springboot学习(2)

    WebMvcConfigurerAdapter 在springboot2.0及以上版本过时问题 WebMvcConfigurerAdapter已经过时,替代方案: 1 实现 WebMvcConfigu ...

  10. java服务端项目开发规范

    更新内容 2015-03-13 (请先更新svn的mybatis.xml.BaseMapper.java.Pager.java文件) 加入测试类规范 加入事物控制规范 加入mapper接口规则 ...