package net.northking.cctp.upperComputer.config;

import net.northking.cctp.upperComputer.constants.UpperComputerConstant;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory){
        return new RabbitAdmin(connectionFactory);
    }


    /**
     * 上位机心跳
     * @return
     */
    @Bean("heartQueue")
    public Queue heartQueue(){
        return QueueBuilder.durable(UpperComputerConstant.HEART_MQ_QUEUE_NAME).build();
    }

    @Bean("heartExchange")
    public Exchange heartExchange(){
        return ExchangeBuilder.directExchange(UpperComputerConstant.HEART_MQ_EXCHANGE_NAME).durable(true).build();
    }
    @Bean("heartBinding")
    public Binding heartBinding(@Qualifier("heartQueue")Queue queue,@Qualifier("heartExchange")Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("").noargs();
    }

    /**
     * 性能数据
     * @return
     */
    @Bean("perDataQueue")
    public Queue perDataQueue(){
        return QueueBuilder.durable(UpperComputerConstant.PER_DATA_MQ_QUEUE_NAME).build();
    }

    @Bean("perDataExchange")
    public Exchange perDataExchange(){
        return ExchangeBuilder.directExchange(UpperComputerConstant.PER_DATA_MQ_EXCHANGE_NAME).durable(true).build();
    }
    @Bean("perDataBinding")
    public Binding perDataBinding(@Qualifier("perDataQueue")Queue queue,@Qualifier("perDataExchange")Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("").noargs();
    }

    @Bean("exchangeExchange")
    public Exchange exchangeExchange(){
        return ExchangeBuilder.directExchange(UpperComputerConstant.EXCHANGE_UPPER_COMPUTER_EXCHANGE).durable(true).build();
    }


    @Bean("fixedListenerContainer")
    public SimpleMessageListenerContainer fixedListenerContainer(ConnectionFactory connectionFactory) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);        //这一步非常重要，固定队列模式要，一定要主动设置  SimpleMessageListenerContainer监听容器，监听应答队列
        container.setAcknowledgeMode(AcknowledgeMode.AUTO);//设置确认模式为自动确认
        container.setConcurrentConsumers(2);
        container.setPrefetchCount(5);
        return container;
    }


    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }


}
