package com.muyu.carData.testcontroller;

import com.alibaba.fastjson.JSONObject;
import com.muyu.carData.pojo.Student;
import lombok.extern.log4j.Log4j2;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author：张腾
 * @Package：com.muyu.carData.testcontroller
 * @Project：cloud-server-8
 * @name：KafkaProducerController
 * @Date：2024/9/28 15:10
 */
@RestController
@RequestMapping("/produce")
@Log4j2
public class KafkaProducerController {

    @Autowired
    private KafkaProducer kafkaProducer;

    private final String topicName = "test";

    @GetMapping("/produceTest")
    public String produceTest() {
        try {
            Student stu = Student.builder().id(2)
                    .name("杨闪闪")
                    .sex("男")
                    .build();
            String stuStr = JSONObject.toJSONString(stu);
            log.info("Topic:{}", topicName);
            log.info("Java对象：{}",stu);
            log.info("转换为JSON：{}",stuStr);
            //使用KafkaProducer发送消息
            ProducerRecord<String, String> stringProducerRecord = new ProducerRecord<>(topicName, stuStr);
            kafkaProducer.send(stringProducerRecord);
        }catch (Exception e){
            log.error("Producer写入Topic异常,异常信息是：{}",e.getMessage());
        }
        return "消息发送成功";
    }

}
