RabbitMQ Exchange和Queue不会自动创建

时间:2017-12-11 07:28:29

标签: java rabbitmq spring-amqp spring-rabbit spring-rabbitmq

我创建了一个新的spring应用程序,它将消息发送到rabbitmq服务器。 我的rabbitMQConfig java文件如下所示:

@Configuration
public class RabbitMQConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQConfig.class);

    @Value("${spring.rabbitmq.host}")
    private String SPRING_RABBITMQ_HOST;

    @Value("${spring.rabbitmq.port}")
    private int SPRING_RABBITMQ_PORT;

    @Value("${spring.rabbitmq.username}")
    private String SPRING_RABBITMQ_USERNAME;

    @Value("${spring.rabbitmq.password}")
    private String SPRING_RABBITMQ_PASSWORD;

    @Bean
    public RabbitTemplate rabbitTemplate(){
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(SPRING_RABBITMQ_HOST,SPRING_RABBITMQ_PORT);
        connectionFactory.setUsername(SPRING_RABBITMQ_USERNAME);
        connectionFactory.setPassword(SPRING_RABBITMQ_PASSWORD);
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setExchange("my.controller.exchange");
        rabbitTemplate.setRoutingKey("my.controller.key");
        return rabbitTemplate;
    }

    @Bean
    DirectExchange exchange() {
            return new DirectExchange("my.controller.exchange", true, false);
    }

    @Bean
    public Queue queue() {
            return new Queue("my.controller", true);
    }

    @Bean
    Binding exchangeBinding(DirectExchange exchange, Queue queue) {
            return BindingBuilder.bind(queue).to(exchange).with("my.controller.key");
    }
}

以下是我如何将消息推送到队列:

@Service
public class RabbitPublisher {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private static Logger LOGGER = Logger.getLogger(RabbitPublisher.class);

    public  Boolean  pushToMyQueue(HashMap<String, Object> message) {
        try {
            rabbitTemplate.convertAndSend("my.controller.exchange","my.controller.key",message);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("Error in pushing to my queue", e);
        }
        return false;
    }
}

由于rabbitmq服务器上的交换和队列不存在,我希望它们能够自动创建并推送消息。但它会导致以下错误:

ERROR 18198 --- [168.201.18:5672] o.s.a.r.c.CachingConnectionFactory       : 
Channel shutdown: channel error; protocol method: #method<channel.close>
(reply-code=404, reply-text=NOT_FOUND - no exchange 
'my.controller.exchange' in vhost '/', class-id=60, method-id=40)

当我创建交换和队列并在服务器上手动绑定它们时,会成功推送消息。 如果我错过了什么,请告诉我。感谢。

2 个答案:

答案 0 :(得分:4)

您需要添加RabbitAdmin @Bean。管理员将在首次打开连接时声明元素。

答案 1 :(得分:0)

您必须使用所需的连接工厂添加AmqpAdmin管理员Bean,如下所示:

description = json["desc"]