package com.zzsn.test;

import com.alibaba.fastjson.JSON;
import com.zzsn.crawler.WeixinSiteThread;
import com.zzsn.entity.ClbAnsProcessitem;
import com.zzsn.entity.SiteMsgTemple;
import com.zzsn.job.KafkaConsumerJob;
import com.zzsn.util.Constants;
import org.apache.kafka.clients.CommonClientConfigs;
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.apache.kafka.common.serialization.StringDeserializer;

import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class MsgReceiver {

    public static void main(String[] args) {
        wxOfficialConsumer();
    }
    public static void wxOfficialConsumer (){
        //1.创建消费者
        KafkaConsumer<String, String> consumer = createConsumer();
        consumer.subscribe(Arrays.asList(Constants.KAFKA_PRODUCT_TOPIC));

        try{
            while(true){
                //消费者是一个长期运行的程序，通过持续轮询向Kafka请求数据。在其他线程中调用consumer.wakeup()可以退出循环
                //在0ms内等待Kafka的broker返回数据.超时参数指定poll在多久之后可以返回，不管有没有可用的数据都要返回
                ConsumerRecords<String, String> records = consumer.poll(0);
                consumer.commitSync();

                for(ConsumerRecord record : records){
                    ClbAnsProcessitem siteMsgTemple = JSON.parseObject(record.value().toString(), ClbAnsProcessitem.class);
                    System.out.println(siteMsgTemple);
                }
            }
        }catch (Exception e){
            consumer = createConsumer();
            consumer.subscribe(Arrays.asList(Constants.KAFKA_PRODUCT_TOPIC));
        }

    }

    private static KafkaConsumer<String, String> createConsumer() {
        Properties properties = new Properties();
        properties.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, Constants.KAFKA_CONSUMER_SERVERS);
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, Constants.KAFKA_CONSUMER_GROUP_ID);
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
        //kafka数据的读取方式
        properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,Constants.KAFKA_CONSUMER_AUTO_OFFSET_RESET);
//         latest earliest
        //时间间隔设置为1h
        properties.put("max.poll.interval.ms", 60*60*1000);
        properties.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 1);
        return new KafkaConsumer<>(properties);
    }
}
