All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.zodiac.autoconfigure.rabbit.RabbitMQAutoConfiguration Maven / Gradle / Ivy

There is a newer version: 1.6.8
Show newest version
package org.zodiac.autoconfigure.rabbit;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.RabbitConnectionFactoryBean;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.util.ClassUtils;
import org.zodiac.commons.constants.SystemPropertiesConstants;
import org.zodiac.core.constants.AppConstants;
import org.zodiac.rabbit.EnhancedRabbitTemplate;
import org.zodiac.rabbit.RabbitRetryInfo;
import org.zodiac.rabbit.RabbitSSLInfo;
import org.zodiac.rabbit.RabbitTemplateInfo;
import org.zodiac.rabbit.aop.delay.DelayQueueScaner;
import org.zodiac.rabbit.logger.AbstractTraceLog;
import org.zodiac.rabbit.logger.DatabaseMySQLTraceLogger;
import org.zodiac.rabbit.logger.NoopTraceLogger;
import org.zodiac.rabbit.logger.Slf4jTraceLogger;
import org.zodiac.rabbit.utils.LogbackUtil;

@SpringBootConfiguration
@Import(value = {RabbitMQAnnotationDrivenConfiguration.class})
//@EnableConfigurationProperties(value = {RabbitConfigProperties.class})
@ConditionalOnProperty(name = SystemPropertiesConstants.Zodiac.SPRING_RABBITMQ_CONFIG_ENABLED, havingValue = "true")
@ConditionalOnClass(value = {org.springframework.amqp.rabbit.core.RabbitTemplate.class, com.rabbitmq.client.Channel.class})
public class RabbitMQAutoConfiguration {

    public static Environment appEnv;
    public static final String RABBIT_TRACE_LOG_TYPE_KEY = "rabbit.trace.log-type";
    public static final String RABBIT_TRACE_LOG_TYPE_FILE = "file";

    public static final String RABBIT_TRACE_LOG_TYPE_MYSQL = "mysql";

    public static final String RABBIT_TRACE_LOG_TYPE_NONE = "none";

    private RabbitConfigProperties rabbitConfigProperties;

    private Environment environment;

    private DataSource dataSource;

    public RabbitMQAutoConfiguration(RabbitConfigProperties rabbitConfigProperties, Environment environment,
        ObjectProvider dataSource) {
        this.rabbitConfigProperties = rabbitConfigProperties;
        this.environment = environment;
        this.dataSource = dataSource.getIfAvailable();
    }

//    @Bean
//    @ConfigurationProperties(prefix = SystemPropertiesConstants.Zodiac.SPRING_RABBITMQ_CONFIG_PREFIX, ignoreInvalidFields = true)
//    protected RabbitConfigProperties rabbitConfigProperties() {
//        return new RabbitConfigProperties();
//    }

    @SpringBootConfiguration
    @ConditionalOnClass(name = {"ch.qos.logback.classic.LoggerContext"})
    // @ConditionalOnProperty(prefix = SystemPropertiesConstants.Zodiac.SPRING_RABBITMQ_PREFIX, name = "enabled",
    // havingValue = "true")
    protected static class LogbackCreator {

        @PostConstruct
        public void init() {
            LogbackUtil.getLogger("traceLog", ch.qos.logback.classic.Level.INFO, "rabbit");
        }
    }

    @SpringBootConfiguration
    @ConditionalOnClass(name = {"org.apache.logging.log4j.core.LoggerContext"})
    // @ConditionalOnProperty(prefix = SystemPropertiesConstants.Zodiac.SPRING_RABBITMQ_PREFIX, name = "enabled",
    // havingValue = "true")
    protected static class Log4jCreator {

        @PostConstruct
        public void init() {
            // Log4j2Util.getLogger("traceLog", "rabbit", "%d{yyyy-MM-dd HH:mm:ss.SSS} [%-10T] [%-5level] %l - %m%n");
        }
    }

    @SpringBootConfiguration
    @ConditionalOnClass(value = {org.springframework.amqp.rabbit.core.RabbitMessagingTemplate.class})
    @ConditionalOnMissingBean(value = {org.springframework.amqp.rabbit.core.RabbitMessagingTemplate.class})
    @Import(RabbitTemplateConfiguration.class)
    @ConditionalOnProperty(prefix = SystemPropertiesConstants.Zodiac.SPRING_RABBITMQ_CONFIG_PREFIX, name = "enabled", havingValue = "true")
    protected static class MessagingTemplateConfiguration {

        @Bean
        @ConditionalOnSingleCandidate(value = org.springframework.amqp.rabbit.core.RabbitTemplate.class)
        protected org.springframework.amqp.rabbit.core.RabbitMessagingTemplate
            rabbitMessagingTemplate(org.springframework.amqp.rabbit.core.RabbitTemplate rabbitTemplate) {
            return new org.springframework.amqp.rabbit.core.RabbitMessagingTemplate(rabbitTemplate);
        }

    }

    @SpringBootConfiguration
    @ConditionalOnMissingBean(value = {ConnectionFactory.class})
    protected static class RabbitConnectionFactoryConfiguration {

        @Bean
        protected CachingConnectionFactory rabbitConnectionFactory(RabbitConfigProperties config) throws Exception {
            RabbitConnectionFactoryBean factory = new RabbitConnectionFactoryBean();
            if (config.determineHost() != null) {
                factory.setHost(config.determineHost());
            }
            factory.setPort(config.determinePort());
            if (config.determineUsername() != null) {
                factory.setUsername(config.determineUsername());
            }
            if (config.determinePassword() != null) {
                factory.setPassword(config.determinePassword());
            }
            if (config.determineVirtualHost() != null) {
                factory.setVirtualHost(config.determineVirtualHost());
            }
            if (config.getRequestedHeartbeat() != null) {
                factory.setRequestedHeartbeat((int)config.getRequestedHeartbeat().getSeconds());
            }
            RabbitSSLInfo ssl = config.getSsl();
            if (ssl.isEnabled()) {
                factory.setUseSSL(true);
                if (ssl.getAlgorithm() != null) {
                    factory.setSslAlgorithm(ssl.getAlgorithm());
                }
                factory.setKeyStore(ssl.getKeyStore());
                factory.setKeyStorePassphrase(ssl.getKeyStorePassword());
                factory.setTrustStore(ssl.getTrustStore());
                factory.setTrustStorePassphrase(ssl.getTrustStorePassword());
            }
            if (config.getConnectionTimeout() != null) {
                factory.setConnectionTimeout((int)config.getConnectionTimeout().toMillis());
            }
            factory.afterPropertiesSet();
            CachingConnectionFactory connectionFactory = new CachingConnectionFactory(factory.getObject());
            connectionFactory.setAddresses(config.determineAddresses());
            connectionFactory.setPublisherConfirms(config.isPublisherConfirms());
            connectionFactory.setPublisherReturns(config.isPublisherReturns());
            if (config.getCache().getChannel().getSize() != null) {
                connectionFactory.setChannelCacheSize(config.getCache().getChannel().getSize());
            }
            if (config.getCache().getConnection().getMode() != null) {
                connectionFactory.setCacheMode(config.getCache().getConnection().getMode());
            }
            if (config.getCache().getConnection().getSize() != null) {
                connectionFactory.setConnectionCacheSize(config.getCache().getConnection().getSize());
            }
            if (config.getCache().getChannel().getCheckoutTimeout() != null) {
                connectionFactory
                    .setChannelCheckoutTimeout(config.getCache().getChannel().getCheckoutTimeout().toMillis());
            }
            return connectionFactory;
        }

    }

    @SpringBootConfiguration
    @Import(value = {RabbitConnectionFactoryConfiguration.class})
    @ConditionalOnProperty(prefix = SystemPropertiesConstants.Zodiac.SPRING_RABBITMQ_CONFIG_PREFIX, name = "enabled", havingValue = "true")
    protected static class RabbitTemplateConfiguration {

        private final ObjectProvider messageConverter;

        private final RabbitConfigProperties properties;

        public RabbitTemplateConfiguration(ObjectProvider messageConverter,
            RabbitConfigProperties properties) {
            this.messageConverter = messageConverter;
            this.properties = properties;
        }

        @Bean
        @ConditionalOnMissingBean(value = {AmqpAdmin.class})
        @ConditionalOnSingleCandidate(value = ConnectionFactory.class)
        //@ConditionalOnProperty(prefix = "spring.rabbitmq", name = "dynamic", matchIfMissing = true)
        @ConditionalOnProperty(prefix = SystemPropertiesConstants.Zodiac.SPRING_RABBITMQ_CONFIG_PREFIX, name = "enabled", havingValue = "true")
        protected AmqpAdmin amqpAdmin(ConnectionFactory connectionFactory,
            org.springframework.amqp.rabbit.core.RabbitTemplate rabbitTemplate,
            SimpleRabbitListenerContainerFactoryConfigurer listenerContainerCOnfigurer) {
            AmqpAdmin amqpAdmin = new RabbitAdmin(connectionFactory);
            if (rabbitTemplate instanceof EnhancedRabbitTemplate) {
                EnhancedRabbitTemplate enhancedRabbitTemplate = (EnhancedRabbitTemplate)rabbitTemplate;
                enhancedRabbitTemplate.setRabbitAdmin(amqpAdmin);
            }
            listenerContainerCOnfigurer.setRetryAmqpAdmin(amqpAdmin);
            listenerContainerCOnfigurer.setRetryRabbitTemplate(rabbitTemplate);
            return amqpAdmin;
        }

        private RetryTemplate createRetryTemplate(RabbitRetryInfo retry) {
            RetryTemplate template = new RetryTemplate();
            SimpleRetryPolicy policy = new SimpleRetryPolicy();
            policy.setMaxAttempts(retry.getMaxAttempts());
            template.setRetryPolicy(policy);
            ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
            backOffPolicy.setInitialInterval(retry.getInitialInterval().toMillis());
            backOffPolicy.setMultiplier(retry.getMultiplier());
            backOffPolicy.setMaxInterval(retry.getMaxInterval().toMillis());
            template.setBackOffPolicy(backOffPolicy);
            return template;
        }

        @Bean
        protected DelayQueueScaner
            DelayQueueScaner(org.springframework.amqp.rabbit.core.RabbitTemplate rabbitTemplate) {
            return new DelayQueueScaner(rabbitTemplate);
        }

        private boolean determineMandatoryFlag() {
            Boolean mandatory = this.properties.getTemplate().getMandatory();
            return (mandatory != null ? mandatory : this.properties.isPublisherReturns());
        }

        @Bean
        @ConditionalOnSingleCandidate(value = ConnectionFactory.class)
        @ConditionalOnMissingBean(value = {org.springframework.amqp.rabbit.core.RabbitTemplate.class})
        protected org.springframework.amqp.rabbit.core.RabbitTemplate
            rabbitTemplate(ConnectionFactory connectionFactory, Environment environment) {
            org.springframework.amqp.rabbit.core.RabbitTemplate rabbitTemplate =
                new EnhancedRabbitTemplate(connectionFactory,
                    environment.getProperty(SystemPropertiesConstants.Spring.SPRING_APP_NAME, AppConstants.UNKNOWN));
            MessageConverter messageConverter = this.messageConverter.getIfUnique();
            if (messageConverter != null) {
                rabbitTemplate.setMessageConverter(messageConverter);
            }
            rabbitTemplate.setMandatory(determineMandatoryFlag());
            RabbitTemplateInfo templateProperties = this.properties.getTemplate();
            RabbitRetryInfo retryProperties = templateProperties.getRetry();
            if (retryProperties.isEnabled()) {
                rabbitTemplate.setRetryTemplate(createRetryTemplate(retryProperties));
            }
            if (templateProperties.getReceiveTimeout() != null) {
                rabbitTemplate.setReceiveTimeout(templateProperties.getReceiveTimeout().toMillis());
            }
            if (templateProperties.getReplyTimeout() != null) {
                rabbitTemplate.setReplyTimeout(templateProperties.getReplyTimeout().toMillis());
            }
            return rabbitTemplate;
        }

    }

    @PostConstruct
    public void init() {
        appEnv = environment;
        if (environment.containsProperty(RABBIT_TRACE_LOG_TYPE_KEY)) {
            String type = environment.getProperty(RABBIT_TRACE_LOG_TYPE_KEY);
            if (type.equals(RABBIT_TRACE_LOG_TYPE_FILE)) {
                AbstractTraceLog.setTraceLogger(Slf4jTraceLogger.instance);
            } else if (type.equals(RABBIT_TRACE_LOG_TYPE_MYSQL)) {
                AbstractTraceLog.setTraceLogger(
                    new DatabaseMySQLTraceLogger(dataSource, rabbitConfigProperties.getTracer().getQueueCapacity()));
            } else if (type.equals(RABBIT_TRACE_LOG_TYPE_NONE)) {
                AbstractTraceLog.setTraceLogger(NoopTraceLogger.instance);
            }
        } else {
            if (dataSource != null && ClassUtils.isPresent(rabbitConfigProperties.getTracer().getJdbcDriverName(),
                RabbitMQAutoConfiguration.class.getClassLoader())) {
                AbstractTraceLog.setTraceLogger(
                    new DatabaseMySQLTraceLogger(dataSource, rabbitConfigProperties.getTracer().getQueueCapacity()));
            } else {
                AbstractTraceLog.setTraceLogger(Slf4jTraceLogger.instance);
            }
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy