kafka消費者實例-簡潔可用

 版本:kafka-clients-0.11.0.1.jar

不囉嗦直接看代碼:

package com.z.kafka;

import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.Properties;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.slf4j.Logger;

import com.zjb.PropertiesUtil;

public class ConsumerUtil {
	
	private static final String GROUP = "testGrp";
	private static final long TIMEOUT_MS = 100;
	private static String BROKER_LIST = "127.0.0.1:9092";
    private static String DECODER = "org.apache.kafka.common.serialization.StringDeserializer";

	private KafkaConsumer<String, String> initConsumer(String grpId) {
		Properties pro = new Properties();
		
		pro.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BROKER_LIST);
		pro.setProperty(ConsumerConfig.CLIENT_ID_CONFIG, "client_test2");
		pro.setProperty(ConsumerConfig.GROUP_ID_CONFIG, grpId);
		pro.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
		pro.setProperty(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
		pro.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, DECODER );
		pro.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, DECODER );
		
		KafkaConsumer<String, String> consumer = new KafkaConsumer<String,String>(pro);
		return consumer;
	}

	public KafkaConsumer<String,String> getConsumer(String topic, String group){
		
		String grp = GROUP;
		if(group != null){
			grp = group;
		}
		
		return initConsumer(grp);
	}
	
	public static void main(String[] args) {
		
		String topic = "test_topic";
		String group = "test_grp";
		
		System.out.println("topic:{"+topic+"},group:{"+GROUP+"}");
		KafkaConsumer consumer = new ConsumerUtil().getConsumer(topic, group);
		consumer.subscribe(Arrays.asList(topic));
	     while (true) {
	         ConsumerRecords<String, String> records = consumer.poll(100);
	         for (ConsumerRecord<String, String> record : records){
	        	System.out.println(record.value());
	         }
	     }
	}
	
}

實例說明:

消費者參數沒有太多需要操心的,集羣地址配置正確,然後再指定一個消費分組就ok。

有問題的話,歡迎評論區指正。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章