如何使用 Spring Framework 在 RabbitMQ Java 配置类中设置多个主题? [英] How to setup multiple topics in a RabbitMQ Java config class using Spring Framework?

查看:33
本文介绍了如何使用 Spring Framework 在 RabbitMQ Java 配置类中设置多个主题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Spring Framework 创建一个 RabbitMQ 配置类.该文档没有说明如何在 TopicExchange 中设置多个主题.我怎么做?到目前为止,我有这个 Java 代码,但我不清楚如何在下面的绑定方法中设置多个主题,因为它只返回一个绑定.如果我需要多个主题,我是否不需要多个绑定?

I'm trying to create a RabbitMQ configuration class using Spring Framework. The documentation does not say anything on how to setup multiple topics in a TopicExchange. How do I do that? So far, I have this Java code but I'm not clear on how to setup multiple topics in the binding method below since it only returns one binding. Would I not need multiple bindings if I need multiple topics?

@Configuration
@EnableRabbit
public class MessageReceiverConfiguration {

    final static String queueName = "identity";
    final static String topic1 = "NewUserSignedUp";
    final static String topic2 = "AccountCreated";

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Bean
    Queue queue() {
        return new Queue(queueName, false);
    }

    @Bean
    TopicExchange exchange() {
        return new TopicExchange("DomainEvents");
    }   

    @Bean
    Binding binding(Queue queue, TopicExchange exchange) {
        // How to setup multiple topics?
        return BindingBuilder.bind(queue).to(exchange).with(topic1);
    }

    @Bean
    SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {

        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();

        container.setConnectionFactory(connectionFactory);
        container.setQueueNames(queueName);
        container.setMessageListener(listenerAdapter);
        container.setAcknowledgeMode(AcknowledgeMode.AUTO);

        return container;
    }

    @Bean
    MessageReceiver receiver() {
        return new MessageReceiver();
    }

    @Bean
    MessageListenerAdapter listenerAdapter(MessageReceiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }    

}

推荐答案

您可以通过更改 Binding 函数返回列表而不是单个 Binding 对象来定义多个绑定.

You can define multiple binding by changing Binding function to return a list instead of a single Binding object.

@Bean
List<Binding> bindings() {

    return Arrays.AsList(BindingBuilder.bind(queue()).to(exchange()).with(topic1), 
                        BindingBuilder.bind(queue()).to(exchange()).with(topic2));
}

提示:您不需要将队列和交换作为方法参数传递.可以直接引用bean的方法来传递exchange和queue的信息.

Tip: You do not need to pass queue and exchange as method params. You can directly refer the bean methods to pass the information of exchange and queue.

参考文档 了解更多详情.

这篇关于如何使用 Spring Framework 在 RabbitMQ Java 配置类中设置多个主题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆