package com.seer.teach.teacher.mq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.stereotype.Component;

import jakarta.annotation.PreDestroy;
import java.util.concurrent.ConcurrentHashMap;

@Component("teacherRocketMQProducerFactory")
@Slf4j
public class RocketMQProducerFactory {

    private static final ConcurrentHashMap<String, DefaultMQProducer> producers = new ConcurrentHashMap<>();

    private RocketMQProducerFactory() {}

    /**
     * 获取或创建一个 RocketMQ 生产者实例
     *
     * @param producerGroup 生产者组名
     * @param namesrvAddr   NameServer 地址
     * @return DefaultMQProducer 实例
     */
    //dev
    public static DefaultMQProducer getProducer(String producerGroup, String namesrvAddr)  {
        //dev
        return producers.computeIfAbsent(producerGroup, group -> {
            try {
                DefaultMQProducer producer = new DefaultMQProducer(group);
                producer.setNamesrvAddr(namesrvAddr);
                producer.start();
                return producer;
            } catch (MQClientException e) {
                log.error(e.getMessage(),e);
            }
            return null;
        });
    }

    /**
     * 关闭所有生产者实例
     */
    @PreDestroy
    public static void shutdownAll() {
        producers.forEach((group, producer) -> producer.shutdown());
        producers.clear();
    }
}
