package com.pcloud.common.core.mq;

import java.util.HashMap;
import java.util.Map;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.pcloud.common.core.constant.MQQueueConstant;
import com.pcloud.common.core.constant.MQTopicProducer;

/**
 * RabbitMQ
 * 
 * @author：songx
 * @date：2018年8月16日,上午11:22:49
 */
@Configuration
public class RabbitMQFactory {

	private static final String DEAD_LETTER_EXCHANGE = "rays.dlx";

	private static final String DEAD_ROUTING_KEY = "rays.dlk";

	private static TopicExchange topicExchange = null;

	/**
	 * 声明业务队列同时与死信队列绑定，当业务队列的消息失败时会转发到死信队列中在进行处理，防止信息丢失
	 * 
	 * @param queueName
	 *            队列名称
	 * @return
	 */
	public static Queue queueBuilder(String queueName) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("x-dead-letter-exchange", DEAD_LETTER_EXCHANGE);// 设置死信交换机
		map.put("x-dead-letter-routing-key", DEAD_ROUTING_KEY);// 设置死信routingKey
		return QueueBuilder.durable(queueName).withArguments(map).build();
	}

	@Bean
	public Queue deadQueue() {
		return new Queue(MQQueueConstant.DEAD);
	}

	@Bean
	public DirectExchange deadLetterExchange() {
		return new DirectExchange(DEAD_LETTER_EXCHANGE, true, false);
	}

	@Bean
	public Binding deadBinding() {
		return BindingBuilder.bind(deadQueue()).to(deadLetterExchange()).with(DEAD_ROUTING_KEY);
	}

	/**
	 * Topic模式下生产者与消费者到交换机的绑定
	 * 
	 * @param queue
	 *            消费者队列
	 * @param producer
	 *            生产者名称
	 * @return
	 */
	public static Binding bindingExchange(Queue queue, String producer) {
		return BindingBuilder.bind(queue).to(getTopicExchange()).with(producer);
	}

	@Bean
	TopicExchange topicExchange() {
		return getTopicExchange();
	}

	/**
	 * 
	 * @return
	 */
	private static TopicExchange getTopicExchange() {
		if (topicExchange == null) {
			topicExchange = new TopicExchange(MQTopicProducer.EXCHAGE);
		}
		return topicExchange;
	}

}
