package com.muyu.kafka;

import com.alibaba.fastjson.JSON;
import com.muyu.iotDB.service.IotDbServer;
import com.muyu.mqtt.dao.MessageData;
import lombok.extern.log4j.Log4j2;
import org.apache.iotdb.rpc.IoTDBConnectionException;
import org.apache.iotdb.rpc.StatementExecutionException;
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.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.rmi.ServerException;
import java.time.Duration;
import java.util.*;

/**
 * 定时器 SimpleKafkaConsumer
 *
 * @author Yangle
 * Date 2024/6/16 22:18
 */
@Component
@Log4j2
public class SimpleKafkaConsumer {

    @Resource
    private IotDbServer iotDbServer;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @KafkaListener(topics = "test1", groupId = "Topics")
    public void consume(ConsumerRecord<String, String> record) {
        log.info("开始消费");
        try {
            System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
            String value = record.value();
            log.info("value:{}", value);
            MessageData messageData1 = com.alibaba.fastjson2.JSONObject.parseObject(value, MessageData.class);
            log.info("messageData1:{}", messageData1);
            iotDbServer.add(messageData1);
        } catch (Exception e) {
            log.error("Error consuming Kafka message", e);
            // 处理异常，可能需要重试或其他逻辑
        }
    }

    @KafkaListener(topics = "test2", groupId = "Topics")
    public void consume2(ConsumerRecord<String, String> record) {
        log.info("开始消费");
        try {
            System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
            String value = record.value();
            log.info("value:{}", value);
            MessageData messageData1 = com.alibaba.fastjson2.JSONObject.parseObject(value, MessageData.class);
            log.info("messageData1:{}", messageData1);
            iotDbServer.add(messageData1);
        } catch (Exception e) {
            log.error("Error consuming Kafka message", e);
            // 处理异常，可能需要重试或其他逻辑
        }
    }


}

