package com.seer.teach.user.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
@Slf4j
public class RocketMQProducerFactory {

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

    private RocketMQProducerFactory() {}

    /**
     * 获取或创建一个 RocketMQ 生产者实例
     *
     * @param producerGroup 生产者组名
     * @param namesrvAddr   NameServer 地址
     * @return DefaultMQProducer 实例
     */
    public static DefaultMQProducer getProducer(String producerGroup, String namesrvAddr) throws MQClientException {
        return producers.computeIfAbsent(producerGroup, group -> {
            try {
                DefaultMQProducer producer = new DefaultMQProducer(group);
                // 设置为 10 秒
                producer.setSendMsgTimeout(10000);
                // 发送失败时重试 3 次
                producer.setRetryTimesWhenSendFailed(3);
                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();
    }
}
