package cn.reghao.tnb.search.esapp.log.mq;

import cn.reghao.jutil.jdk.serializer.JsonConverter;
import cn.reghao.jutil.jdk.web.log.NginxLog;
import cn.reghao.tnb.search.esapp.config.AppProperties;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * @author reghao
 * @date 2022-04-02 11:20:37
 */
@Component
public class KafkaPub {
    private final String topic;
    private final Producer<String, String> producer;

    public KafkaPub(AppProperties appProperties) {
        this.topic = appProperties.getKafkaTopic();

        Properties properties = new Properties();
        properties.put("bootstrap.servers", appProperties.getKafkaUri());
        properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        this.producer = new KafkaProducer<>(properties);
    }

    public void produce(NginxLog nginxLog) {
        String json = JsonConverter.objectToJson(nginxLog);
        ProducerRecord<String, String> record = new ProducerRecord<>(topic, "nginx-log", json);
        producer.send(record);
    }
}
