package com.xingxi.common.mq.core;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;

import java.util.List;

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

/**
 * @ClassName BaseMessageReceiver
 * @projectName xingxi
 * @Deacription // TODO
 * @Author FZ.Dong
 * @Date 2020/9/15 15:24
 * @Version 1.0
 **/



@Slf4j
public abstract class AbstractRabbitConsumer extends AbstractRabbit implements ChannelAwareMessageListener {


    /**
     * 取得exchange和queue绑定信息， 默认调用bind，也可自行实现
     *
     * @return
     */
    protected abstract List<Binding> getBindingList();


    /**
     * 处理消息
     *
     * @param body
     * @param channel
     * @param message
     * @return true:自动确认消息，false:自己try...cach,自己确认消息
     * @throws Exception
     */
    public abstract boolean execute(String body, Channel channel, Message message) throws Exception;


    /**
     * 收到消息后的处理事件
     *
     * @param message
     * @param channel
     * @throws Exception
     */
    protected void convertMessage(Message message, Channel channel) throws Exception {
        long tag = message.getMessageProperties().getDeliveryTag();
        try {
            String body = new String(message.getBody(), UTF_8);
            if (execute(body, channel, message)) {
                channel.basicAck(tag, false);
            }
        } catch (Exception ex) {
            channel.basicNack(tag, false, false);
            log.error("消息处理失败", ex);
        }
    }


}
