package com.muyu.processing.config;

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
public class ReturnsCallbackConfig implements RabbitTemplate.ReturnsCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 当前bean初始化的时候执行
     */
    @PostConstruct
    public void init() {
        this.rabbitTemplate.setReturnsCallback(this);
    }

    /**
     * 消息发送达到 queue 失败执行
     *
     * @param returnedMessage the returned message and metadata.
     */
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        System.out.println("消息" + returnedMessage.getMessage().toString() +
                "被交换机" + returnedMessage.getExchange() + "回退！"
                + "退回原因为：" + returnedMessage.getReplyText());
        // TODO 回退了所有的信息，可做补偿机制
    }
}
