package com.pcloud.common.core.mq;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.connection.SingleConnectionFactory;

/**
 * @描述：
 * @作者：songx
 * @创建时间：2017年9月14日,上午10:48:02
 * @版本：1.0
 */
@Configuration
@PropertySource(value = "classpath:public_system.properties")
public class ActiveMqFactory {

    /**
     *
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ActiveMqFactory.class);

    @Value("${mq.brokerURL}")
    private String brokerURL;

    /**
     * 初始化Mq连接
     *
     * @return
     */
    @Bean(name = "connectionFactory")
    public ActiveMQConnectionFactory getMqConnection() {
        LOGGER.info("【ActiveMq】初始化MQ链接.<START>");
        ActiveMQConnectionFactory mqConnection = new ActiveMQConnectionFactory();
        mqConnection.setBrokerURL(brokerURL);
        mqConnection.setTrustAllPackages(true);
        return mqConnection;
    }

    /**
     * 初始化JMS连接池
     *
     * @return
     */
    @Autowired
    @Bean("cachingConnectionFactory")
    public CachingConnectionFactory getCachingConnectionFactory(ActiveMQConnectionFactory connectionFactory) {
        CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(connectionFactory);
        cachingConnectionFactory.setReconnectOnException(true);
        cachingConnectionFactory.setCacheConsumers(false);
        cachingConnectionFactory.setCacheProducers(false);
        cachingConnectionFactory.setSessionCacheSize(50);
        return cachingConnectionFactory;
    }

    /**
     * Spring用于管理真正的ConnectionFactory的ConnectionFactory
     *
     * @return
     */
    @Autowired
    @Bean(name = "singleConnectionFactory")
    public SingleConnectionFactory getSingleConnection(CachingConnectionFactory cachingConnectionFactory) {
        LOGGER.info("【ActiveMq】初始化spring管理JMS链接.<START>");
        SingleConnectionFactory singleConnection = new SingleConnectionFactory();
        singleConnection.setTargetConnectionFactory(cachingConnectionFactory);
        return singleConnection;
    }
}
