欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

RabbitMQ 整合SpringBoot 项目 ——Failed to check/redeclare auto-delete queue(s).

程序员文章站 2022-04-05 19:43:42
...

项目背景:
Java 代码实现连接RabbitMQ:

public static Connection getConnection() throws Exception {
        //定义连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置服务地址
        factory.setHost("localhost");
        //端口
        factory.setPort(5672);
        //设置账号信息,用户名、密码、vhost
        factory.setVirtualHost("testhost");
        factory.setUsername("admin");
        factory.setPassword("admin");
        // 通过工程获取连接
        Connection connection = factory.newConnection();
        return connection;
    }

请注意此处的ConnectionFactory 的包路径是:import com.rabbitmq.client.ConnectionFactory;

如果改为SpringBoot注入的方式写为:

@Configuration
public class RabbitMQConfig {
    /**
    *此处的ConnectionFactory 如果还是用com.rabbitmq.client.ConnectionFactory;
    * 也没有毛病,一样可以配置相关属性。但是启动的时候就是报异常:
    * 
    * Failed to check/redeclare auto-delete queue(s).
    */
    @Bean
    public ConnectionFactory connectionFactory(){
        //定义连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置服务地址
        factory.setHost("localhost");
        //端口
        factory.setPort(5672);
        //设置账号信息,用户名、密码、vhost
        factory.setVirtualHost("testhost");
        factory.setUsername("admin");
        factory.setPassword("admin");
    }
}

项目在启动时报错:
Failed to check/redeclare auto-delete queue(s).
在调试的时候发现明明指定了连接的服务器是MQ服务器地址,但是还是会找本地服务器。

RabbitMQ 整合SpringBoot 项目 ——Failed to check/redeclare auto-delete queue(s).

直接创建CachingConnectionFactory解决问题,原因在于:导入的包路径错误!下面是正确的写法:

@Bean
public org.springframework.amqp.rabbit.connection.ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        //设置服务地址
        connectionFactory .setHost("localhost");
        //端口
        connectionFactory .setPort(5672);
        //设置账号信息,用户名、密码、vhost
        connectionFactory .setVirtualHost("testhost");
        connectionFactory .setUsername("admin");
        connectionFactory .setPassword("admin");

        return connectionFactory;
    }
相关标签: 中间件 RabbitMQ