package com.fdkankan.rabbitmq.callback;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/**
 * <p>
 * TODO
 * </p>
 *
 * @author dengsixing
 * @since 2022/4/19
 **/
@Slf4j
@Component
public class ProducerCallback implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback {

    //confirms模式：无论exchange投递消息是成功或是失败，都会返回ack，我们可以根据返回的ack是成功还是失败，做相应的业务处理
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String messageId = correlationData.getId();
        //投递成功
        if(ack){
            log.info("消息投递成功，id:{}", messageId);
            return;
        }
        //投递失败
        log.error("消息投递失败，id:{}，失败原因:{}", messageId, cause);
    }

    //return模式：只有exchange投递消息失败时，才会执行回调函数，来做一些相应的业务处理
    @Override
    public void returnedMessage(Message returnedMessage, int replyCode, String replyText, String exchange, String routingKey) {
        log.info("消息从Exchange路由到Queue失败: exchange: {}, route: {}, replyCode: {}, replyText: {}, message: {}", exchange, routingKey, replyCode, replyText, returnedMessage);

    }
}
