访问messageListener onMessage中的connectionfactory

时间:2017-01-27 00:38:23

标签: spring-boot rabbitmq spring-amqp spring-rabbitmq

我正在创建一个rabbitmq messageListener,并希望能够在onMessage方法中访问connectionfactory配置,这可能吗?它对于记录和其他细节很有用。能够记录发送消息的vhost会很有帮助,并且消息本身不可用。这是我的消费者和配置

public class Consumer implements MessageListener {

    @Override
    public void onMessage(Message message) {
    //how can I get the connection factory configuration when a message is     sent?
    }

这是配置

{
    @Configuration
    @EnableAutoConfiguration
    public class RabbitConfig {

    private static final String SIMPLE_MESSAGE_QUEUE = "qDLX2.dlq";

    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new     CachingConnectionFactory("server");
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("ad,om");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("vhost1");
        return connectionFactory;
    }

    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        return template;
    }



    @Autowired
    private Consumer consumer;


    @Bean
    public SimpleMessageListenerContainer listenerContainer() {
         SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer();        
        listenerContainer.setConnectionFactory(connectionFactory());
        listenerContainer.setQueueNames(SIMPLE_MESSAGE_QUEUE);
        listenerContainer.setMessageListener(consumer);
        listenerContainer.setAcknowledgeMode(AcknowledgeMode.AUTO);      
        return listenerContainer;
    }


}

由于 格雷格

1 个答案:

答案 0 :(得分:0)

没有标准的方法。

您可以将连接工厂注入consumer bean定义中的listenerContainer字段...

listenerContainer.setMessageListener(this.consumer);
this.consumer.setConnectionFactory(connectionFactory());

你也可以@Autowire

然后,您可以使用getRabbitConnectionFactory().getVirtualHost()访问虚拟主机。