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

项目背景:
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)._第1张图片

直接创建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)