package com.bcxin.ars.rabbitmq; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitAdmin; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; import org.springframework.retry.backoff.ExponentialBackOffPolicy; import org.springframework.retry.support.RetryTemplate; /** * @author linqinglin * @date 2018/12/14 0014 16:36 */ @Configuration @PropertySource("classpath:rabbitmq.properties") public class RabbitConfig { @Autowired private Environment env; /** * 连接服务配置 * @return */ @Bean public ConnectionFactory rabbitConnectionFactory(){ CachingConnectionFactory factory = new CachingConnectionFactory( env.getProperty("rabbitmq.host"), env.getProperty("rabbitmq.port", Integer.class) ); factory.setUsername(env.getProperty("rabbitmq.username")); factory.setPassword(env.getProperty("rabbitmq.password")); return factory; } /** * 通过指定下面的admin信息,当前producer中的exchange和queue会在rabbitmq服务器上自动生成 * @param rabbitConnectionFactory * @return */ @Bean public RabbitAdmin rabbitAdmin(ConnectionFactory rabbitConnectionFactory){ RabbitAdmin rabbitAdmin=new RabbitAdmin(rabbitConnectionFactory); //设置忽略声明异常 rabbitAdmin.setIgnoreDeclarationExceptions(true); return rabbitAdmin; } /** * RabbitTemplate配置,RabbitTemplate接口定义了发送和接收消息的基本操作 * @param rabbitConnectionFactory * @return */ @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) //必须是prototype类型 public RabbitTemplate rabbitTemplate(ConnectionFactory rabbitConnectionFactory){ RabbitTemplate rabbitTemplate=new RabbitTemplate(rabbitConnectionFactory); RetryTemplate retryTemplate = new RetryTemplate(); ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy(); backOffPolicy.setInitialInterval(500); backOffPolicy.setMultiplier(10.0); backOffPolicy.setMaxInterval(10000); retryTemplate.setBackOffPolicy(backOffPolicy); rabbitTemplate.setRetryTemplate(retryTemplate); return rabbitTemplate; } }