package com.seer.teach.user.mq;

import com.seer.teach.common.enums.im.ImMqTopicEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;

@Slf4j
@Component
public class MqProducer {

    @Value("${zs.rocket-mq.namesrvAddr:192.168.0.39:9876}")
    private String namesrvAddr;

    @Value("${zs.rocket-mq.producerGroup:${spring.profiles.active:dev}}")
    private String producerGroup;

    public void sendMsg(String topic, String tag, String businessKey, String body) {
        log.info("开始发送消息，businessKey ：{}，body : {}", businessKey, body);
        try {
            DefaultMQProducer producer = RocketMQProducerFactory.getProducer(topic + "-" + producerGroup, namesrvAddr);

            Collection<Message> messages = new ArrayList<>();
            Message msg = new Message(ImMqTopicEnum.USER_INFO.getTopic() + "-" + producerGroup, tag, businessKey, body.getBytes());
            messages.add(msg);
            SendResult send = producer.send(messages);
            log.info("send message result: {}", send);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
