最近研究RabbitMQ从本地获取配置,主要场景是RabbitMQ的连接配置如:ip地址这些需要从外部的配置服务器获取。面对这个问题,有两个解决方案,一个是用RabbitMQ原生的连接方式,但是如果使用了spring boot这个方法就有点笨拙,所以推荐使用重写RabbitMQ的工厂类ConnectionFactory类来进行连接RabbitMQ。

  

public class RabbitmqConfig {

    @Bean
public ConnectionFactory connectionFactory() throws Exception {
//创建工厂类
CachingConnectionFactory cachingConnectionFactory=new CachingConnectionFactory();
//用户名
cachingConnectionFactory.setUsername("gust");
//密码
cachingConnectionFactory.setPassword("gust");
//rabbitMQ地址
cachingConnectionFactory.setHost("127.0.0.1");
//rabbitMQ端口
cachingConnectionFactory.setPort(Integer.parseInt(5672));
cachingConnectionFactory.setCacheMode(CachingConnectionFactory.CacheMode.CHANNEL);
return cachingConnectionFactory; } /**
* 将配置好的信息放入
* @param connectionFactory
* @return
*/
@Bean
public RabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory){
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
return factory;
} /**
* 自动声明队列
* @param connectionFactory
* @return
*/
@Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory){
RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
rabbitAdmin.setAutoStartup(true);
return rabbitAdmin;
}
}
05-27 14:46