当前位置:   article > 正文

SpringBoot2整合了Rabbitmq以后,有些情景不需要初始化和连接Rabbitmq,所以需要怎么处理呢?

SpringBoot2整合了Rabbitmq以后,有些情景不需要初始化和连接Rabbitmq,所以需要怎么处理呢?

        问题提出,最近有个需求,有的场合项目需要连接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})

         读取配置的配置类:

  1. @Data
  2. @Component
  3. @ConfigurationProperties(prefix = "spring.rabbitmq")
  4. public class MyRabbitMqConfig {
  5. /**
  6. * 服务是否启用
  7. * true是启用
  8. * false是禁用
  9. */
  10. private boolean enable;
  11. /**
  12. * 主机ip
  13. */
  14. private String host;
  15. /**
  16. * 服务端ip
  17. */
  18. private int port;
  19. /**
  20. * 用户名
  21. */
  22. private String username;
  23. /**
  24. * 密码
  25. */
  26. private String password;
  27. /**
  28. * 虚拟主机
  29. */
  30. private String virtualHost;
  31. }

        RabbitTemplate和ConnectionFactory配置:

  1. @Configuration
  2. public class RabbitMqConfig {
  3. @Resource
  4. private MyRabbitMqConfig rabbitMqConfig;
  5. @Bean
  6. public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
  7. RabbitTemplate rabbitTemplate=new RabbitTemplate();
  8. rabbitTemplate.setConnectionFactory(connectionFactory);
  9. return rabbitTemplate;
  10. }
  11. @Bean
  12. public ConnectionFactory connectionFactory() {
  13. CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
  14. connectionFactory.setHost(rabbitMqConfig.getHost());
  15. connectionFactory.setPort(rabbitMqConfig.getPort());
  16. connectionFactory.setUsername(rabbitMqConfig.getUsername());
  17. connectionFactory.setPassword(rabbitMqConfig.getPassword());
  18. connectionFactory.setVirtualHost(rabbitMqConfig.getVirtualHost());
  19. return connectionFactory;
  20. }
  21. }

        这样通过配置yml中的spring.rabbitmq.enable属性即可,如果设置成true是启用,如果设置成false是禁用。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/52789
推荐阅读
相关标签
  

闽ICP备14008679号