问题提出,最近有个需求,有的场合项目需要连接Rabbitmq,有些场合项目就不需要连接,再不需要连接的时候,还必须的安装Rabbimq服务,徒增时间消耗,所以需要处理一下。
在yml中配置如下:
spring:
rabbitmq:
# 配置rabbitMq启用开关
enable: true
host: xxx.xx.xxx.xxx
port: 5672
username: xxx
password: xxxxxxxx!
virtualHost: /xxxx
启动类中配置如下,禁用springboot的自动配置:
@SpringBootApplication(exclude = {RabbitAutoConfiguration.class})
读取配置的配置类:
@Data
@Component
@ConfigurationProperties(prefix = "spring.rabbitmq")
public class MyRabbitMqConfig {/*** 服务是否启用* true是启用* false是禁用*/private boolean enable;/*** 主机ip*/private String host;/*** 服务端ip*/private int port;/*** 用户名*/private String username;/*** 密码*/private String password;/*** 虚拟主机*/private String virtualHost;}
RabbitTemplate和ConnectionFactory配置:
@Configuration
public class RabbitMqConfig {@Resourceprivate MyRabbitMqConfig rabbitMqConfig;@Beanpublic RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {RabbitTemplate rabbitTemplate=new RabbitTemplate();rabbitTemplate.setConnectionFactory(connectionFactory);return rabbitTemplate;}@Beanpublic ConnectionFactory connectionFactory() {CachingConnectionFactory connectionFactory = new CachingConnectionFactory();connectionFactory.setHost(rabbitMqConfig.getHost());connectionFactory.setPort(rabbitMqConfig.getPort());connectionFactory.setUsername(rabbitMqConfig.getUsername());connectionFactory.setPassword(rabbitMqConfig.getPassword());connectionFactory.setVirtualHost(rabbitMqConfig.getVirtualHost());return connectionFactory;}}
这样通过配置yml中的spring.rabbitmq.enable属性即可,如果设置成true是启用,如果设置成false是禁用。