消费kafka0.10简单实例

##简介 kafka0.10,消费topic的话,可以不用知道zk的地址,只要broker的地址即可

##maven

        <dependency>
			<groupId>org.apache.kafka</groupId>
			<artifactId>kafka-clients</artifactId>
			<version>0.10.0.0</version>
		</dependency>

##消费

/**
 * java -jar -Dfile.encoding=utf-8 \
 *  kafka-consumer-0.0.1-SNAPSHOT.jar \
 *  localhost:9092 topicname groupid earliest
 */
@SpringBootApplication
public class KafkaConsumerApplication {

	private static volatile boolean isStop = false;

	public static void main(String[] args) {
		SpringApplication.run(KafkaConsumerApplication.class, args);
		Runtime.getRuntime().addShutdownHook(new Thread(){
			@Override
			public void run() {
				isStop = true;
			}
		});
	}

	@Bean
	public CommandLineRunner consumeKafka(){
		return new CommandLineRunner() {
			@Override
			public void run(String... strings) throws Exception {
				String bootstrap = strings[0];
				String topic = strings[1];
				String group = strings[2];
				String offset = strings[3];

				Properties props = new Properties();
				props.put("bootstrap.servers", bootstrap);
				props.put("group.id", group);
				props.put("enable.auto.commit", "true");  //自动commit
				props.put("auto.commit.interval.ms", "1000"); //定时commit的周期
				props.put("session.timeout.ms", "30000"); //consumer活性超时时间
				props.put("auto.offset.reset",offset);
				props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
				props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
				props.put("key.deserializer.encoding", "UTF8");
				props.put("value.deserializer.encoding", "UTF8");
				KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
				consumer.subscribe(Arrays.asList(topic));
				while (!isStop) {
					ConsumerRecords<String, String> records = consumer.poll(Long.MAX_VALUE);
					for (ConsumerRecord<String, String> record : records){
						try{
							System.out.println(record);
						}catch (Exception e){
							e.printStackTrace();
						}
					}
				}
			}
		};
	}
}

##github

转载于:https://my.oschina.net/go4it/blog/810189

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值