package com.miyzh.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * @Description: RabbitConfig
 * @Author: lyt
 * @Date: 2019/6/21 11:21
 */
@Configuration
public class RabbitConfig {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${spring.rabbitmq.host}")
    private String host;

    @Value("${spring.rabbitmq.port}")
    private int port;

    @Value("${spring.rabbitmq.username}")
    private String username;

    @Value("${spring.rabbitmq.password}")
    private String password;

    public static final String EXCHANGE_TEST = "testExchange";

    public static final String QUEUE_TEST = "testMq";

    public static final String QUEUE_TEST1 = "test";

    public static final String ROUTINGKEY_TEST = "testMq";

    public static final String ROUTINGKEY_TEST1 = "test";

    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host,port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setPublisherConfirms(true);
        return connectionFactory;
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    //必须是prototype类型
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        return template;
    }


    @Bean
    public DirectExchange testExchange() {
        return new DirectExchange(EXCHANGE_TEST);
    }
    @Bean
    public Queue queueTest() {
        //队列持久
        return new Queue(QUEUE_TEST, true);
    }

    @Bean
    public Queue queueTest1() {
        //队列持久
        return new Queue(QUEUE_TEST1, true);
    }
    @Bean
    public Binding bindingTest() {
        return BindingBuilder.bind(queueTest()).to(testExchange()).with(RabbitConfig.ROUTINGKEY_TEST);
    }

    @Bean
    public Binding bindingTest1() {
        return BindingBuilder.bind(queueTest1()).to(testExchange()).with(RabbitConfig.ROUTINGKEY_TEST1);
    }
}
