package com.upyuns.platform.rs.universal.mq;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * 项目中Mq的自动配置
 *
 * @author Vangelis
 * @date 2019-06-01 20:36
 */
@Configuration
@Slf4j
@AllArgsConstructor
public class MQAutoConfiguration {
    private final ConnectionFactory connectionFactory;
    @Bean
    @Scope("prototype")
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        //开启回调 必须设置为true
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback((correlationData,ack,cause)->{
            //实现消息到达交换器的回调方法
            log.info("RabbitMQ sendMessage-->confirm-->start correlationData:{},ack:{},cause:{}",correlationData,ack,cause);
            log.info("RabbitMQ sendMessage-->confirm-->end");
        });
        rabbitTemplate.setReturnCallback((message,replyCode,replyText,exchange,routingKey)->{
            //实现消息到达队列的回调方法
            log.info("RabbitMQ sendMessage-->returnedMessage-->start message:{},replyCode:{},replyText:{},exchange:{},routingKey:{}"
                    ,message.toString(),replyCode,replyText,exchange,routingKey);
            log.info("RabbitMQ sendMessage-->returnedMessage-->end");
        });

        return rabbitTemplate;
    }

    /**
     *  监听器中默认封装实现
     */
    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory() {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setConcurrentConsumers(3);
        factory.setMaxConcurrentConsumers(10);
        return factory;
    }
}
