package org.ts.ddcs.kafka;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.ts.ddcs.log.LogHelper;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;


/**
 * MQ数据处理主类
 *
 * @author dylan
 */
@Data
@Component
public class KafkaClient {

    @Resource
    private KafkaTemplate kafkaTemplate;

    @PostConstruct
    public void init() {
        try {
            KafkaClientHolder.newInstance().setKafkaClient(this);
        } catch (Exception e) {
            LogHelper.error(e);
        }
    }

    /**
     * 发送KAFKA消息
     *
     * @param topic 主题
     * @param body  消息
     */
    public static void messageSubmit(String topic, String body) {
        KafkaTemplate client = KafkaClientHolder.newInstance().getKafkaClient().getKafkaTemplate();
        if (null != client) {
            ListenableFuture<SendResult> future = client.send(topic, body);
            future.addCallback(new ListenableFutureCallback<SendResult>() {
                @Override
                public void onFailure(Throwable throwable) {
                    throwable.printStackTrace();
                }

                @Override
                public void onSuccess(SendResult sendResult) {

                }
            });
        }
    }
}
