package com.miyzh.rabbitMQ;

import com.miyzh.config.RabbitConfig;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;


@Component
public class MsgProducer implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback,ChannelAwareMessageListener {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //由于rabbitTemplate的scope属性设置为ConfigurableBeanFactory.SCOPE_PROTOTYPE，所以不能自动注入
    private RabbitTemplate rabbitTemplate;

    /**
     * 构造方法注入rabbitTemplate
     */
    @Autowired
    public MsgProducer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        //rabbitTemplate如果为单例的话，那回调就是最后设置的内容
        rabbitTemplate.setConfirmCallback(this);

    }

    public void sendMsg(String msg) {
        //消息唯一性
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
        System.out.println("发送消息。。。。");
//        rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_TEST, RabbitConfig.ROUTINGKEY_TEST, msg, correlationId);
        rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_TEST, RabbitConfig.ROUTINGKEY_TEST1, msg, correlationId);
    }

    /**
     *
     * @description: 消息成功发送到队列回调
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        logger.info(" 回调id:" + correlationData);
        if (b) {
            logger.info("消息发送成功");
        } else {
            logger.info("消息发送失败:" + s);
        }
    }

    /**
     * @description: 消息失败后return回调
     */
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        logger.error("return--message:"+new String(message.getBody())+",replyCode:"+replyCode+",replyText:"+replyText+",exchange:"+exchange+",routingKey:"+routingKey);
    }

    /**
     * @description: 消息送达后回调
     */
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        try{
            logger.info("consumer--:"+message.getMessageProperties()+":"+new String(message.getBody()));
            //成功消费，消息从队列中删除
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch(Exception e){
            //requeue=true，消息重新进入队列，false被删除
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }
    }
}
