package com.muyu.carData.consumer;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.muyu.carData.pojo.Student;
import lombok.extern.log4j.Log4j2;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Collection;

/**
 * @Author：张腾
 * @Package：com.muyu.carData.consumer
 * @Project：cloud-server-8
 * @name：MyKafkaConsumer
 * @Date：2024/9/26 15:42
 */
@Component
@Log4j2
public class MyKafkaConsumer implements InitializingBean {

    @Autowired
    private KafkaConsumer kafkaConsumer;

    private final String topicName = "test";

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("启动线程开始监听topic:{}",topicName);
        Thread thread = new Thread(() -> {
            ThreadUtil.sleep(1000);
            Collection<String> topics = Lists.newArrayList(topicName);
            kafkaConsumer.subscribe(topics);
            while (true){
                ConsumerRecords<String,String> consumerRecords = kafkaConsumer.poll(Duration.ofMillis(1000));
                for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
                    //从consumerRecord中获取消费数据
                    String value = consumerRecord.value();
                    log.info("从Kafka中消费的原始数据：{}",value);
                    //转换为java对象
                    Student stu = JSONUtil.toBean(value, Student.class);
                    log.info("消费数据转换为Java对象：{}",stu);
                }
            }
        });
        thread.start();
    }
}
