package com.palmnest.model.kafka;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

/**
 * kafka消费者类
 *
 * @author wangxz
 * <p>
 * 2018年10月29日
 */
public class KafkaConsumerServer {

	private Properties props;

	public KafkaConsumerServer() {
	}

	public KafkaConsumerServer(Properties props) {
		super();
		this.props = props;
	}

	public Properties getProps() {
		return props;
	}

	public void setProps(Properties props) {
		this.props = props;
	}

	public String receive() {

		KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);
		consumer.subscribe(Arrays.asList(props.getProperty("topic")));

		String msg = "";
		while (true) {
			ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofMillis(100));
			for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
				msg += consumerRecord.value();
			}
			consumer.close();
			return msg;
		}
	}

}
