package com.muyu.common.kafka.config;

import com.muyu.common.core.text.StrFormatter;
import com.muyu.common.kafka.constant.KafkaConfigConstants;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;

/**
 * @Author: wangXin
 * @Date 2024/9/28 16:35
 * @Description Kafka生产者配置
 */
@Configuration
public class KafkaProducerConfig {

    /**
     * 服务端IP
     */
    @Value("${kafka.producer.bootstrap-servers-ip}")
    private String bootstrapServersIP;

    /**
     * 服务端口号
     */
    @Value("${kafka.producer.bootstrap-servers-port}")
    private String bootstrapServersPort;

    /**
     * 重试次数
     */
    @Value("${kafka.producer.retries}")
    private Integer retries;

    /**
     * 默认批量大小
     */
    @Value("${kafka.producer.batch-size}")
    private Integer batchSize;

    /**
     * 总内存字节数
     */
    @Value("${kafka.producer.buffer-memory}")
    private Integer bufferMemory;

    /**
     * 偏移量
     */
    @Value("${kafka.producer.acks}")
    private String acks;

    /**
     * Kafka生产者初始化配置
     * @return kafka生产者实例
     */
    @Bean
    public KafkaProducer<String, String> kafkaProducer() {
        HashMap<String, Object> configs = new HashMap<>();
        configs.put(KafkaConfigConstants.BOOTSTRAP_SERVERS,
                StrFormatter.format("{}:{}", bootstrapServersIP, bootstrapServersPort));
        configs.put(KafkaConfigConstants.RETRIES, retries);
        configs.put(KafkaConfigConstants.BATCH_SIZE, batchSize);
        configs.put(KafkaConfigConstants.BUFFER_MEMORY, bufferMemory);
        configs.put(KafkaConfigConstants.ACKS, acks);
        Serializer<String> keySerializer = new StringSerializer();
        Serializer<String> valueSerializer = new StringSerializer();
        return new KafkaProducer<>(configs, keySerializer, valueSerializer);
    }
}
