package com.xingxi.common.mq.core;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.util.UUID;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * @ClassName AbstractRabbitPublisher
 * @projectName xingxi
 * @Deacription
 * @Author FZ.Dong
 * @Date 2020/9/16 11:39
 * @Version 1.0
 **/

public class AbstractRabbitPublisher extends AbstractRabbit{

    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRabbitPublisher.class);

    /**
     * 产发送消息
     * @param message
     * @param exchange
     * @param routingKey
     */
    protected <T> void send(T message, String exchange, String routingKey) {

        RabbitTemplate tmp = new RabbitTemplate(connectionFactory);
        tmp.setMandatory(true);
        tmp.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                LOGGER.debug("corrData:{},ack:{},cause:{}", correlationData, ack, cause);
            }
        });

        byte[] body = JSON.toJSONString(message).getBytes(UTF_8);
        Message mq = new Message(body, new MessageProperties());
        mq.getMessageProperties().setMessageId(UUID.randomUUID().toString());
        tmp.send(exchange, routingKey, mq);
    }

}
