package com.css.simulation.resource.common.adapter.controller;

import api.common.pojo.param.KafkaParameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/kafka")
@Slf4j
public class KafkaController {

    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;

    // -------------------------------- 带回调函数的发送 --------------------------------
    @RequestMapping("/send")
    public void send(@RequestBody @Validated KafkaParameter kafkaParameter) {
        kafkaTemplate.send(kafkaParameter.getTopic(), kafkaParameter.getData()).addCallback(success -> {
            // 消息发送到的topic
            String topic = success.getRecordMetadata().topic();
            // 消息发送到的分区
            int partition = success.getRecordMetadata().partition();
            // 消息在分区内的offset
            long offset = success.getRecordMetadata().offset();
            log.info("------- 发送消息成功：\n"
                    + "主题 topic 为：" + topic + "\n"
                    + "分区 partition 为：" + partition + "\n"
                    + "偏移量为：" + offset + "\n"
                    + "消息体为：" + kafkaParameter.getData());
        }, failure -> {
            log.error("发送消息失败:" + failure.getMessage());
        });
    }


}
