簡體   English   中英

Spring 3 和 Rabbit MQ 集成(不是 Spring 引導)

[英]Spring 3 and Rabbit MQ integration (not Spring Boot)

我很難讓 Spring 3 應用程序與 RabbitMQ 集成,以便從隊列接收消息(我不需要發送消息)。

部分挑戰在於現在的大部分文檔都與 Spring 引導有關。 相關的 Spring 指南很有幫助,但按照這些步驟在我的情況下似乎不起作用。 例如,該指南包括以下文字:

消息偵聽器容器和接收器 bean 是您偵聽消息所需的全部內容。

因此,我使用以下代碼設置了偵聽器容器和接收器 bean。

設置消息處理程序

@Component
public class CustomMessageHandler {

    public void handleMessage(String text) {
        System.out.println("Received: " + text);
    }
}

設置配置

@Configuration
public class RabbitConfig {

    @Bean
    public RabbitTemplate rabbitTemplate(final ConnectionFactory connectionFactory){
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setRoutingKey("queue-name");
        return rabbitTemplate;
    }

    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost("...host...");
        connectionFactory.setPort(5671);
        connectionFactory.setVirtualHost("...virtual host..");
        connectionFactory.setUsername("...username...");
        connectionFactory.setPassword("...password...");
        return connectionFactory;
    }

    @Bean
    public MessageListenerAdapter messageListenerAdapter(CustomMessageHandler messageHandler) {
        return new MessageListenerAdapter(messageHandler, "handleMessage");
    }

    @Bean
    public SimpleMessageListenerContainer listenerContainer(ConnectionFactory connectionFactory,
                                                            MessageListenerAdapter messageListenerAdapter) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setQueueNames("queue-name");
        container.setConnectionFactory(connectionFactory);
        container.setMessageListener(messageListenerAdapter);
        return container;
    }
}

不幸的是,使用此設置,應用程序將啟動,但它永遠不會觸發消息處理程序。 它嘗試讀取的隊列中也有一條消息,等待被消費。

關於丟失或配置錯誤的任何想法?

感謝@GaryRussell 提供的一些依賴管理幫助,我能夠看到 spring-rabbit 和 spring-amqp 的版本太新了。 不幸的是,使用較舊的 1.3.9.RELEASE 會增加額外的挑戰。

其他一些幫助以使用實際 RabbitMQ Java 客戶端的形式出現。 這個選項實現起來要簡單得多,並且避免了依賴問題。 最終我需要包含以下依賴項:

<dependency>
    <groupId>com.rabbitmq</groupId>
    <artifactId>amqp-client</artifactId>
    <version>5.7.3</version>
</dependency>

然后我只是按照他們關於創建連接使用消息的文檔進行操作。

瞧,它有效!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM