package com.muyu.common.rabbit.config;

import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 消息发送到队列的确认
 */
@Component
@Log4j2
public class ReturnCallbackConfig implements RabbitTemplate.ReturnsCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * @PostContruct是spring框架的注解，在⽅法上加该注解会在项⽬启动的时候执⾏该⽅法，也可以理解为在spring容器初始化的时候执
     */
    @PostConstruct
    public void init() {
        rabbitTemplate.setReturnsCallback(this);
    }

    /**
     * 消息发送失败 则会执行这个方法
     *
     * @param returnedMessage the returned message and metadata.
     */
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        log.error("消息：{}，被交换机：{} 回退！退回原因为：{}",
                returnedMessage.getMessage().toString(), returnedMessage.getExchange(), returnedMessage.getReplyText());
        // TODO 回退了所有的信息，可做补偿机制
    }

}
